In React, useEffect and useState

In React, useEffect and useState are two of the most commonly used hooks, each serving different purposes in managing component behavior and state.

1. useState:

useState is a hook that allows you to create and manage state in functional components.

Usage:

  • Initialize State: You pass the initial state value to useState.
  • Read State: It returns a state variable, which you can read at any time.
  • Update State: It provides a function that allows you to update the state and re-render the component.

Example:

import { useState } from 'react';

function Counter() {
  // Declare a state variable `count` and a function `setCount` to update it
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}
  • Initial State: useState(0) initializes the count to 0.
  • Updating State: When the button is clicked, setCount updates the count state, causing the component to re-render with the new value.

2. useEffect:

useEffect is a hook that lets you perform side effects in functional components. Side effects include things like data fetching, subscriptions, DOM manipulation, timers, etc.

Usage:

  • Run Effects: It runs after the component renders or updates.
  • Dependencies: You can control when it runs by specifying dependencies (e.g., run only when certain state variables change).

Example:

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    // Effect: Fetch data from an API
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Empty array as dependency means it runs only on mount (componentDidMount equivalent)

  return (
    <div>
      {data ? <p>Data: {JSON.stringify(data)}</p> : <p>Loading...</p>}
    </div>
  );
}
  • Effect Logic: The function inside useEffect will run after the component renders, which is used here to fetch data.
  • Dependencies: [] means the effect runs only on the initial render (component mount), similar to componentDidMount in class components.

Key Features:

  • No Dependencies: If you omit the dependency array, the effect will run after every render.
  • With Dependencies: You can pass specific state or props in the array to only trigger the effect when those values change.
  • Cleanup: You can return a cleanup function inside useEffect to run logic when the component unmounts or before the effect runs again.
useEffect(() => {
  const timer = setInterval(() => {
    console.log('Tick');
  }, 1000);

  return () => {
    clearInterval(timer); // Cleanup on unmount or before rerunning the effect
  };
}, []);

Differences:

FeatureuseStateuseEffect
PurposeHolds state values in a functional componentHandles side effects (e.g., data fetching, subscriptions)
Triggers Re-renderYes, when state is updated with the setter functionNo, it runs after render but does not trigger re-renders itself
UsageTo track and update values that affect renderingTo perform actions based on component lifecycle or state changes
RunsInitializes on component mount and updates state as neededRuns after every render, or when specific dependencies change
ExamplesCounter, form inputs, toggle switchesFetching data, API calls, timers, subscriptions

Summary:

  • useState is for managing state (i.e., data that changes over time).
  • useEffect is for performing side effects (i.e., actions outside the React component rendering, such as API calls, setting up subscriptions, etc.).

They are often used together in applications, where useEffect performs some operation that updates the state with useState.

Leave a Reply

Your email address will not be published. Required fields are marked *

Deprecated: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in /var/www/html/wp-includes/formatting.php on line 4720