</>
Skip to content
React lessons (17/47)

React — Hooks

What are Hooks?

Hooks are functions that let you use state and other React features in function components.

Built-in Hooks

HookPurpose
useStateAdd state to function components
useEffectPerform side effects
useContextConsume context
useRefAccess DOM elements
useReducerManage complex state
useMemoMemoize values
useCallbackMemoize functions

useState

import { useState } from 'react';

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

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>
                Increment
            </button>
        </div>
    );
}

useEffect

import { useEffect } from 'react';

function Timer() {
    const [seconds, setSeconds] = useState(0);

    useEffect(() => {
        const interval = setInterval(() => {
            setSeconds(s => s + 1);
        }, 1000);

        return () => clearInterval(interval);
    }, []);

    return <p>Seconds: {seconds}</p>;
}

Rules of Hooks

  1. Only call hooks at the top level
  2. Only call hooks from React functions
  3. Call hooks from custom hooks
// ✅ Correct
function MyComponent() {
    const [state, setState] = useState(0);
}

// ❌ Wrong
function MyComponent() {
    if (condition) {
        const [state, setState] = useState(0); // Don't do this!
    }
}

Custom Hooks

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;
}

// Usage
function MyComponent() {
    const { width, height } = useWindowSize();
    return <p>Window: {width} x {height}</p>;
}

Mini Practice

Write React code that:

  1. Uses useState hook
  2. Uses useEffect hook
  3. Creates a custom hook
  4. Follows the rules of hooks

Up Next

Next: Learn about useState hook.

Related Topics

Frequently Asked Questions about Hooks

What is Hooks in React?

Hooks is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Hooks?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Hooks.

Why is Hooks important in React?

Hooks is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.