The Difference Between useEffect and useState Hooks in React

React, the popular JavaScript library for building user interfaces, introduced Hooks as a way to manage stateful logic and side effects in functional components. Two of the most commonly used Hooks are ‘useState' and ‘useEffect'. While they might seem similar at first glance, they serve distinct purposes in React applications. Let’s delve into each one to understand their differences and when to use them.

useState Hook:

The ‘useState' Hook is used for managing state within functional components. It allows you to declare state variables and update them over the course of your component’s lifecycle. Here’s a simple example to illustrate its usage:

import React, { useState } from 'react';

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

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

In this example, ‘useState' is used to declare a state variable ‘count' initialized to ‘0'. ‘setCount' is a function provided by ‘useState' that allows us to update the value of ‘count'. Whenever ‘setCount' is called, React will re-render the component with the updated state.

useEffect Hook:

The ‘useEffect' Hook on the other hand is used to perform side effects in functional components. Side effects may include data fetching, subscriptions, or manually changing the DOM. ‘useEffect' accepts a function as its first argument, which will be executed after the component has been rendered to the screen. Let’s see an example:

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

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Empty dependency array means this effect runs only once

  return (
    <div>
      {data ? (
        <p>Data fetched: {data}</p>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

In this example, ‘useEffect' is used to fetch data from an API when the component is first rendered. The empty dependency array [] passed as the second argument ensures that the effect runs only once after the initial render. This prevents unnecessary re-fetching of data on subsequent renders.

Differences:

Now that we’ve seen examples of both Hooks, let’s summarize their differences:

Purpose:

  • useState': Manages state within functional components.
  • 'useEffect': Performs side effects in functional components.

Usage:

  • useState' is used for declaring and updating state variables.
  • 'useEffect‘ is used for performing side effects like data fetching, subscriptions, or DOM manipulation.

Execution:

  • useState' is executed every time the component is rendered.
  • 'useEffect' is executed after the component has been rendered to perform side effects.

Conclusion:

Understanding the differences between ‘useState' and ‘useEffect' is crucial for effectively managing state and side effects in React functional components. By utilizing these Hooks appropriately, you can build React applications that are efficient, maintainable, and scalable.