CodePark/ questions / Hooks & custom hooks
START PRACTICINGPRACTICE
Frontend question · React › Hooks & custom hooks

What is a custom hook? Write one and explain what it shares between components.

function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  useEffect(() => {
    const update = () => setIsOnline(navigator.onLine);
    window.addEventListener('online', update);
    window.addEventListener('offline', update);
    return () => {
      window.removeEventListener('online', update);
      window.removeEventListener('offline', update);
    };
  }, []);
  return isOnline;
}

A custom hook is a JavaScript function whose name starts with use and that calls other hooks. It lets you move stateful logic out of components, so you can reuse and test it separately. Examples are subscribing to the online status or to a media query.

Custom hooks share logic, not state. Each component that calls useOnlineStatus gets its own independent useState and its own effect. If components need the same data, lift the state up, or use context or an external store. An external store is state kept outside React, like a Zustand or Redux store.

The use prefix matters. It tells React and the linter that the function follows the rules of hooks. A function that calls no hooks should be a regular function, without the prefix.

Custom hooks re-run on every render of the calling component. So they always receive fresh props and state.

  • A custom hook is a function starting with use that calls other hooks.
  • It shares stateful logic, not the state itself.
  • Each call gets its own independent state.
  • The use prefix lets the linter enforce the rules of hooks.
  • It re-runs on every render with the latest values.