DEV Community

Cover image for useState and useEffect - React
Vigneshwaran V
Vigneshwaran V

Posted on

useState and useEffect - React

useState

The useState hook is a built-in React function that allows you to add and manage local state within functional components. It tracks data that changes over time and automatically re-renders the component whenever that data is updated.

  • useState is a React Hook that lets you add and manage state in a functional component.

Syntax

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

  • state: The variable holding the current state value.

  • setState: The function used to update the state variable.

  • initialValue: The initial value given to the state variable during the first render. It can be a string, number, boolean, array, object, or null.

Example : Counter

import { useState } from "react";

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

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

export default Counter;
Enter fullscreen mode Exit fullscreen mode

How it works

  • useState(0) initializes count to 0.

  • Clicking the button calls setCount(count + 1).

  • React updates count and re-renders the component.

  • The new value appears on the screen.

Updating State

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

Why use useState?

Without useState

let count = 0;
count++;
Enter fullscreen mode Exit fullscreen mode

The UI won't update because React doesn't know the value changed.

With useState

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

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

React knows the state changed and updates the UI automatically.

  • useState stores data that changes over time.
  • Calling the setter function (setState) triggers a re-render.
  • Never modify state directly.

useEffect

The useEffect Hook is a built-in React function that lets you perform side effects in functional components. Side effects are operations that happen outside the normal rendering process, such as fetching data from an API, updating the document title, setting timers, or adding event listeners.

  • useEffect is a React Hook that lets you perform side effects in a functional component.

Syntax

useEffect(() => {
  // Side effect code
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode
  • Callback Function: Contains the side effect code that React executes.
  • Dependency Array: Controls when the effect should run. It is optional.

Example: Update Document Title

import { useState, useEffect } from "react";

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <h1>{count}</h1>

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

export default Counter;
Enter fullscreen mode Exit fullscreen mode

How it works

  • useState(0) initializes count to 0.
  • When the component renders for the first time, useEffect runs after React updates the UI.
  • Clicking the button calls setCount(count + 1).
  • React updates the count value and re-renders the component.
  • Since count changed, useEffect runs again.
  • The browser tab title is updated with the latest count.

Updating Side Effects

useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]);
Enter fullscreen mode Exit fullscreen mode

Why use useEffect?

Without useEffect

document.title = `Count: ${count}`;
Enter fullscreen mode Exit fullscreen mode

If you write this directly inside the component, it runs every time the component renders, even when it isn't necessary.

With useEffect

useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]);
Enter fullscreen mode Exit fullscreen mode

React runs the effect only when count changes, making your application more efficient.

  • useEffect is used to perform side effects after rendering.
  • It keeps side-effect code separate from rendering logic.
  • The dependency array helps control when the effect should run.

Dependency Array

The dependency array decides when useEffect should execute.

1. No Dependency Array

useEffect(() => {
  console.log("Runs after every render");
});
Enter fullscreen mode Exit fullscreen mode

Output

  • Runs after the initial render.
  • Runs again after every re-render.

2. Empty Dependency Array

useEffect(() => {
  console.log("Runs only once");
}, []);
Enter fullscreen mode Exit fullscreen mode

Output

  • Runs only once after the component is mounted.
  • Commonly used for API calls or initial setup.

3. Dependency Array with Values

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

Output

  • Runs after the first render.
  • Runs again only when count changes.
  • Does not run when other state variables change.

Cleanup Function

Some side effects continue running even after a component is removed. A cleanup function allows React to remove those side effects.

import { useEffect } from "react";

function Timer() {
  useEffect(() => {
    const timer = setInterval(() => {
      console.log("Running...");
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return <h1>Timer Started</h1>;
}

export default Timer;
Enter fullscreen mode Exit fullscreen mode

How it works

  • setInterval() starts a timer.
  • The cleanup function is returned from useEffect.
  • React calls the cleanup function before the component unmounts.
  • clearInterval() stops the timer and prevents memory leaks.

Common Uses of useEffect

  • Fetch data from an API.
  • Update the document title.
  • Start and stop timers.
  • Add and remove event listeners.

NOTE

  • useEffect is used for performing side effects.
  • It runs after React renders the component.
  • The dependency array controls when the effect runs.
  • A cleanup function removes side effects when they are no longer needed.
  • useEffect helps keep your components clean, organized, and efficient.

The useState Hook is used to create and manage state in React functional components, allowing the UI to update whenever the state changes. The useEffect Hook is used to perform side effects such as fetching data, updating the document title, or working with timers after a component renders. Together, these Hooks form the foundation of modern React development, helping you build dynamic, interactive, and maintainable applications.


References

https://www.geeksforgeeks.org/reactjs/reactjs-usestate-hook/
https://www.geeksforgeeks.org/reactjs/reactjs-useeffect-hook/
https://www.w3schools.com/react/react_usestate.asp
https://www.w3schools.com/react/react_useeffect.asp

Top comments (0)