React Hooks Guide

React Hooks Guide

React Hooks revolutionized how we write React components by bringing state and lifecycle features to functional components.

What are React Hooks?

Hooks are functions that let you "hook into" React state and lifecycle features from function components. They let you use state and other React features without writing a class.

Basic Hooks

useState

The useState hook lets you add state to functional components:

import { useState } from 'react';

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

The useEffect hook lets you perform side effects in functional components:

import { useState, useEffect } from 'react';

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

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

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

Advanced Hooks

useContext

useContext lets you subscribe to React context without nesting:

const ThemeContext = createContext('light');

function ThemedComponent() {
  const theme = useContext(ThemeContext);
  return <div className={theme}>...</div>;
}

Custom Hooks

Build your own hooks for reusable logic:

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

  useEffect(() => {
    function handleResize() {
      setSize([window.innerWidth, window.innerHeight]);
    }

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

  return size;
}

Best Practices

  1. Only call hooks at the top level
  2. Use hooks from React functions only
  3. Follow the rules of hooks for predictable behavior
  4. Create custom hooks for complex logic
  5. Use useCallback and useMemo for performance optimization

Hooks have transformed React development by making functional components as powerful as class components while maintaining better readability and reusability.