React Hooks Deep Dive — useState, useEffect, and Beyond

React Hooks Deep Dive — useState, useEffect, and Beyond

Team02 October 2024 Blog, Frontend, Tutorials

Understand how hooks compose logic, avoid infinite renders, and structure effects and custom hooks for maintainable React apps.

useState Basics

const [count, setCount] = useState(0);
const inc = () => setCount(c => c + 1);

useEffect Patterns

useEffect(() => {
  const id = setInterval(() => console.log("tick"), 1000);
  return () => clearInterval(id);   // cleanup
}, []);                              // run once

Custom Hooks

function useOnline() {
  const [online, setOnline] = useState(navigator.onLine);
  useEffect(() => {
    const on = () => setOnline(true);
    const off = () => setOnline(false);
    window.addEventListener("online", on);
    window.addEventListener("offline", off);
    return () => {
      window.removeEventListener("online", on);
      window.removeEventListener("offline", off);
    };
  }, []);
  return online;
}

Common Pitfalls

  • Always list hook dependencies; prefer functions in setState.
  • Do not call hooks inside conditions or loops.
  • Split effects by concern (subscription vs data fetch).