Understanding React Hooks

A deep dive into React Hooks: useState, useEffect, and how they simplify functional components. Hooks let you use state and lifecycle behavior without writing a class, which means less boilerplate, fewer bugs around this, and logic that can be extracted and reused.

useState

Allows you to add state to functional components. It returns a pair: the current value and a setter function that re-renders the component when called:

const [count, setCount] = useState(0);

 <button onClick={() => setCount(count + 1)}>
  Clicked {count} times
 </button>

useEffect

Runs side effects after render — fetching data, subscribing to events, or syncing with the DOM. The dependency array controls when it runs:

useEffect(() => {
  fetch('/api/user').then(r => r.json()).then(setUser);
 }, []); // empty array: run once, after mount

Other Common Hooks

Rules of Hooks

  1. Only call hooks at the top level of a component — never inside loops, conditions or nested functions.
  2. Only call hooks from React functions (components or custom hooks).

These rules exist because React tracks hooks by their call order. Violating them produces the "Rendered more hooks than during the previous render" error.

Custom Hooks

Extract repeated logic into a custom hook — a plain function whose name starts with use:

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
   const onResize = () => setWidth(window.innerWidth);
   window.addEventListener('resize', onResize);
   return () => window.removeEventListener('resize', onResize);
  }, []);
  return width;
 }

Conclusion

Hooks turned React state and side effects into plain functions, which made components smaller, logic reusable, and testing simpler. Start with useState and useEffect, follow the rules of hooks, and extract a custom hook as soon as you notice repetition.

Related Articles

A.M. Rinas

Written by A.M. Rinas

Full-Stack Software Engineer working on web applications, DevOps automation, and databases. More about me on the about page, or say hi through the contact page and LinkedIn.

← Back to all articles