DEV Community

Taaha hussain Khan
Taaha hussain Khan

Posted on

Understanding useState and useEffect in React

React hooks are a powerful way to manage state and side effects in functional components. In this post, we'll explore two of the most commonly used hooks: useState and useEffect.

First, let's start with useState. This hook allows us to add state to our functional components. Here's an example:


jsx
import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};
In this example, we use useState to create a count state variable and a setCount function to update the state. When the user clicks the “Increment” button, the setCount function is called with the new count value.

Next, let’s look at useEffect. This hook allows us to run side effects in our functional components. Here’s an example:

import { useState, useEffect } from 'react';

const UserProfile = ({ userId }) => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(response => response.json())
      .then(data => setUser(data));
  }, [userId]);

  if (!user) return <p>Loading...</p>;

  return (
    <div>
      <h1>{user.name}</h1>
      <p>Email: {user.email}</p>
    </div>
  );
};
In this example, we use useEffect to fetch user data from an API when the component mounts. The second argument to useEffect is an array of dependencies. In this case, we only want to run the effect when the userId prop changes.

By using useState and useEffect, we can manage state and side effects in our functional components. Happy coding!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)