DEV Community

Pranav Bakare
Pranav Bakare

Posted on

UseState and UseEffect Hook in React

In React, useState and useEffect are two fundamental hooks used to manage state and handle side effects in functional components.

1. useState Hook

The useState hook allows you to add state to functional components. It returns an array with two elements:

  1. The current state value.
  2. A function to update that state value.

Example:

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable called 'count' with an initial value of 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      {/* Update state using the setCount function */}
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

In this example:

  • useState(0) initializes the count state variable with a value of 0.
  • setCount is used to update the state when the button is clicked.

2. useEffect Hook

The useEffect hook allows you to perform side effects in your components, such as data fetching, subscriptions, or manually changing the DOM. It takes two arguments:

  1. A function that contains the side effect logic.
  2. An optional array of dependencies that determines when the effect should run.

Example:

import React, { useState, useEffect } from 'react';

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

  // useEffect runs after every render, but the dependency array makes it run only when `count` changes
  useEffect(() => {
    document.title = `You clicked ${count} times`;

    // Cleanup function (optional)
    return () => {
      console.log('Cleanup for count:', count);
    };
  }, [count]); // Dependency array

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default Example;
Enter fullscreen mode Exit fullscreen mode

In this example:

  • useEffect updates the document title whenever count changes.
  • The effect runs after every render if count changes, because count is included in the dependency array.
  • The optional cleanup function runs before the effect runs again or when the component unmounts, which is useful for cleaning up subscriptions or timers.

Both hooks help manage state and side effects in functional components effectively, making React development more concise and powerful.
.
.
.

Let's Summaries....
.
.
.

Here’s a summary of the useState and useEffect hooks in React:

useState Hook

  • Purpose: Manages state in functional components.
  • Syntax: const [state, setState] = useState(initialValue);
  • Parameters:
    • initialValue: The initial state value.
  • Returns:
    • An array with two elements:
    • state: The current state value.
    • setState: Function to update the state.

Example Usage:

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

useEffect Hook

  • Purpose: Handles side effects in functional components, such as data fetching, subscriptions, or manual DOM updates.
  • Syntax: useEffect(() => { /* effect logic */ }, [dependencies]);
  • Parameters:
    • Effect Function: Contains the code to run as a side effect.
    • Dependency Array (optional): List of dependencies that trigger the effect when changed. If empty, the effect runs only once after the initial render. If omitted, the effect runs after every render.
  • Cleanup Function (optional): Returned function from the effect function to clean up resources.

Example Usage:

useEffect(() => {
  document.title = `You clicked ${count} times`;
  return () => {
    // Cleanup logic here
  };
}, [count]);
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • useState simplifies state management in functional components.
  • useEffect handles side effects and can optionally clean up after itself.
  • Both hooks work together to create dynamic, stateful functional components in React.

Top comments (0)