DEV Community

Mahalakshmi C
Mahalakshmi C

Posted on

Hooks in React

What are Hooks?

Hooks are special(Built-in) functions provided by React that allow functional components to use React features such as state, side effects, context, and references.

Hooks were introduced in React 16.8.

Before Hooks, features such as state and lifecycle methods were mainly used with class components. Hooks made it possible to use these features in functional components.

Some commonly used Hooks are:

  • useState
  • useEffect
  • useContext
  • useRef
  • useMemo
  • useCallback

Why Do We Use Hooks?

Hooks are used to:

  • Manage state in functional components
  • Perform side effects
  • Access context data
  • Store references to DOM elements
  • Optimize certain calculations and functions
  • Reuse stateful logic

Rules of Hooks

React has some important rules for using Hooks.

Rule 1: Call Hooks at the Top Level

Do not call Hooks inside:

  • if statements
  • for loops
  • while loops
  • Nested functions

Correct:

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

    return <h1>{count}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Incorrect:

function App() {
    if (true) {
        const [count, setCount] = useState(0);
    }
}
Enter fullscreen mode Exit fullscreen mode

Rule 2: Call Hooks from React Functions

Hooks should be called from:

  • React functional components
  • Custom Hooks

1. useState

useState is used to create and manage state in a functional component.

Example

import { useState } from "react";

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

    return (
        <div>
            <h2>Count: {count}</h2>

            <button onClick={() => setCount(count + 1)}>
                Increase
            </button>
        </div>
    );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Here:

  • count → current state value
  • setCount → function used to update the state
  • 0 → initial value

When setCount changes the value, React re-renders the component.

2. useEffect

useEffect is used to perform side effects in a component.

Examples of side effects include:

  • Fetching data from an API
  • Updating localStorage
  • Setting timers
  • Adding event listeners

Example

import { useEffect, useState } from "react";

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

    useEffect(() => {
        console.log("Count changed:", count);
    }, [count]);

    return (
        <button onClick={() => setCount(count + 1)}>
            {count}
        </button>
    );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Whenever count changes, the effect runs.

3. useRef

useRef is used to store a value that persists between renders without causing a re-render when the value changes.

It is also commonly used to access a DOM element.

Example

import { useRef } from "react";

function InputBox() {
    const inputRef = useRef();

    function focusInput() {
        inputRef.current.focus();
    }

    return (
        <div>
            <input ref={inputRef} />

            <button onClick={focusInput}>
                Focus Input
            </button>
        </div>
    );
}

export default InputBox;
Enter fullscreen mode Exit fullscreen mode

Here, useRef is used to access the input element.

Conclusion

Hooks make functional components more powerful by allowing them to use React features such as state, effects, context, and references. Among them, useState and useEffect are two of the most commonly used Hooks when learning React.

Top comments (0)