DEV Community

Mahalakshmi C
Mahalakshmi C

Posted on

useState and useEffect in React

useState

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

State is a value that can change during the execution of a component. When the state changes, React re-renders the component and updates the UI.

Syntax

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

Here:

  • state → stores the current value
  • setState → updates the value
  • initialValue → initial value of the state

What does useState return?

useState() returns an array containing two values:

[
    current state value,
    setter function
]
Enter fullscreen mode Exit fullscreen mode

For example:

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

Here:

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

The array returned by useState() is commonly destructured into two variables.

Example

import { useState } from "react";

function Counter() {

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

    function increase() {
        setCount(count + 1);
    }

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

            <button onClick={increase}>
                Increase
            </button>
        </div>
    );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

When the button is clicked, setCount() updates the state.

setCount(count + 1);
Enter fullscreen mode Exit fullscreen mode

React then re-renders the component with the new value.

Setter Function

The second value returned by useState() is called the setter function.

For example:

const [name, setName] = useState("Maha");
Enter fullscreen mode Exit fullscreen mode

Here:

name     → current value
setName  → setter function
Enter fullscreen mode Exit fullscreen mode

We should use the setter function to update state:

setName("Lakshmi");
Enter fullscreen mode Exit fullscreen mode

Instead of directly changing the state:

name = "Lakshmi";   // ❌
Enter fullscreen mode Exit fullscreen mode

The setter function tells React that the state has changed and the component needs to be rendered again.

useEffect

useEffect is a React Hook used to perform side effects in a functional component.

A side effect is an operation that happens outside the normal process of calculating and displaying the UI.

Common examples include:

  • Fetching data from an API
  • Updating localStorage
  • Setting a timer
  • Adding event listeners
  • Working with external systems

Syntax

useEffect(() => {
    // side effect code
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

The first argument is a callback function.

The second argument is called the dependency array.

Example

import { useEffect, useState } from "react";

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

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

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

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

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Here, useEffect depends on count:

[count]
Enter fullscreen mode Exit fullscreen mode

Whenever count changes, the effect runs.

Dependency Array

The dependency array controls when the effect runs.

No dependency array

useEffect(() => {
    console.log("Effect runs");
});
Enter fullscreen mode Exit fullscreen mode

The effect runs after every render.

Empty dependency array

useEffect(() => {
    console.log("Effect runs");
}, []);
Enter fullscreen mode Exit fullscreen mode

An empty dependency array means the effect does not depend on changing state or props. It runs after the initial render.

With dependencies

useEffect(() => {
    console.log("Count changed");
}, [count]);
Enter fullscreen mode Exit fullscreen mode

The effect runs after the initial render and again when count changes.


Difference Between useState and useEffect

useState useEffect
Manages state Performs side effects
Stores changing data Runs code after rendering
Updating state causes a re-render Responds to rendering/dependency changes
Example: counter value Example: API call or localStorage

Complete Example Using useState and useEffect

import { useState, useEffect } from "react";

function Counter() {

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

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

    function increase() {
        setCount((previousCount) => previousCount + 1);
    }

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

            <button onClick={increase}>
                Increase
            </button>
        </div>
    );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

How this code works

First:

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

creates a state variable called count with an initial value of 0.

When the button is clicked:

setCount((previousCount) => previousCount + 1);
Enter fullscreen mode Exit fullscreen mode

the setter function updates the state.

After the state changes, React renders the component again.

Then:

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

runs because count has changed.

Simple Flow

useState
   ↓
Creates state + setter function
   ↓
User clicks button
   ↓
Setter function updates state
   ↓
Component re-renders
   ↓
useEffect checks dependency
   ↓
Effect callback runs
Enter fullscreen mode Exit fullscreen mode

Top comments (0)