Commonly Used React Hooks:

  1. useState:

  2. useEffect:

  3. useContext:

  4. useReducer:

  5. useMemo:

  6. useCallback:

  7. useRef:

Why Use Hooks?

Hooks allow you to use state and other React features without writing a class. They enable you to organize the logic inside a component by splitting it into reusable pieces, called Hooks, rather than dividing it by lifecycle methods.

Key Benefits:

Custom Hooks:

You can create your own Hooks to encapsulate and reuse logic across different components. Custom Hooks are just regular functions that can use other Hooks.

Example of a 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 in a component
function Component() {
  const width = useWindowWidth();

  return <div>Window width is: {width}</div>;
}