DEV Community

Cover image for useState() Hook in React
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

useState() Hook in React

React's useState() hook is one of the fundamental hooks you'll often use when building functional components. It allows you to add state to your components, making them dynamic and interactive.

What is useState()?
The useState() hook is a function that lets you add state variables to functional components. Before hooks, only class components could have state, but with hooks, you can now use state in functional components as well.

Image description

Syntax:

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

Enter fullscreen mode Exit fullscreen mode

How useState() Works
When you calluseState(), it returns an array with two elements:

  1. The current state value.
  2. A function that lets you update the state.

Every time you use setState, React triggers a re-render of the component with the updated state.

Example: Simple Counter

import React, { useState } from 'react';

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

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

export default Counter;

Enter fullscreen mode Exit fullscreen mode
  1. We initialize count to 0 using useState(0).
  2. The setCount function is used to update the count when the button is clicked.

Example: Using Objects with useState()

import React, { useState } from 'react';

function UserProfile() {
  const [user, setUser] = useState({ name: 'John Doe', age: 25 });

  const updateName = () => {
    setUser({ ...user, name: 'Jane Doe' });
  };

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={updateName}>Update Name</button>
    </div>
  );
}

export default UserProfile;

Enter fullscreen mode Exit fullscreen mode
  1. We manage an object state representing a user profile.
  2. When updating the state, we use the spread operator (...user) to ensure we only modify the name property, keeping the age unchanged.

Top comments (1)

Collapse
 
rohit413 profile image
Rohit Singh Rajput

Please Update All the hooks with example