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.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay