DEV Community

Cover image for What is useState() and useEffect() in React
Wadi zaatour
Wadi zaatour

Posted on

What is useState() and useEffect() in React

In React, useState and useEffect are two essential hooks used for managing state and side effects in functional components.

useState:

Use case: useState allows you to add state to a functional component. It returns a pair of values: the current state and a function to update that state.
Example:


import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, useState(0) initializes the count state to 0. The setCount function is used to update the count state when the button is clicked.

useEffect:

Use case: useEffect allows you to perform side effects in functional components, such as fetching data, subscribing to events, or updating the document title.
Example:

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

function UserProfile() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    // Fetch user data from an API
    fetch('https://api.example.com/user')
      .then((response) => response.json())
      .then((data) => setUser(data));
  }, []);

  return (
    <div>
      {user ? (
        <div>
          <h2>{user.name}</h2>
          <p>Email: {user.email}</p>
        </div>
      ) : (
        <p>Loading user profile...</p>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, useEffect is used to fetch user data from an API when the component mounts (empty dependency array []). The retrieved data is stored in the user state using setUser, and the component renders the user's name and email when the data is available.

These are just a few basic use cases for useState and useEffect. They are powerful hooks that allow you to handle state and side effects in a declarative way, enabling you to build dynamic and interactive React applications.

Top comments (0)