Have you heard about Hack Frontend Community?Join us on Telegram!
Practice React Problems

Custom Hooks in React: How to Extract and Reuse Logic

Custom Hooks are user-defined functions that use built-in React hooks (useState, useEffect, useMemo, etc.) to encapsulate and reuse logic across different components.

Main rule: custom hook name must start with use so React understands it's a hook and applies corresponding rules.


Why Custom Hooks?

1

Logic encapsulation

You can extract related business logic (e.g., API work, forms, timers) into separate hook and use it in multiple places.

2

Avoiding duplication

Instead of repeating same useEffect or useState in multiple components, you write hook once and reuse it.

3

Improving readability

Components become smaller and cleaner if main logic is extracted into hooks.


Simple Custom Hook Example

Before: without custom hook

function Component() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return <p>Width: {width}px</p>;
}

After: with custom hook

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return width;
}

// Usage
function Component() {
  const width = useWindowWidth();
  return <p>Width: {width}px</p>;
}

Where Custom Hooks Are Used

  • API work (e.g., useFetch, useUserData)
  • Form management (useForm, useInput)
  • Modal, tooltip states (useModal)
  • Local storage work (useLocalStorage)
  • Timers, intervals (useInterval, useDebounce)
  • External library integration (useSocket, useMap)

useLocalStorage Hook Example

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const item = localStorage.getItem(key);
    return item ? JSON.parse(item) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

// Usage
const [theme, setTheme] = useLocalStorage("theme", "light");

Conclusion:

Custom hooks make your code reusable, readable and clean. They help extract repeating logic from components and organize application architecture.

Practice React Problems

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.