React Hooks Deep Dive

(Updated on )

React Hooks Deep Dive

React Hooks are a powerful feature introduced in React 16.8 that allows you to use state and other React features without writing a class. In this guide, we’ll explore the most commonly used hooks and how to use them effectively.

What are React Hooks?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. They don’t work inside classes — they let you use React without classes.

Core Hooks

useState

The most basic hook for managing state in functional components:

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useEffect

Handles side effects in functional components:

function Example() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Fetch data
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Empty array means run once on mount

  return <div>{data ? data.title : 'Loading...'}</div>;
}

useContext

Access context in functional components:

const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Themed Button</button>;
}

Custom Hooks

Create your own hooks to reuse stateful logic:

function useWindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return size;
}

Best Practices

  1. Only call hooks at the top level
  2. Only call hooks from React function components
  3. Use the exhaustive-deps rule for useEffect
  4. Keep hooks focused and single-purpose

Next Steps

Happy coding!