• Introduction In this section, we’ll dive into the useState Hook, a fundamental part of React Hooks. With useState, you can easily manage state in functional components. Follow along with Geek and Gal to learn more about it.
Gal Normal

The useState Hook is a super useful tool to manage state in functional components!

Geek Curious

That sounds cool! How does it work?

Gal Happy

It's super simple! useState returns a pair: the current state value and a function to update it. You can call this function to set a new state!

  • Using useState
Gal Pleased

To use useState, you need to import it from React and call it inside your functional component. It looks like this:

import React, { useState } from 'react';

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

Oh, I see! So you import useState from React and call it inside the functional component. But what's that [count, setCount] part?

Gal Happy

Good question! It's called array destructuring. The useState Hook returns an array with two elements: the current state value and a function to update it. We destructure the array to get those two values separately.

  • Updating State
Gal Pleased

Now let's see how to update the state using the function returned by useState!

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Geek Happy

Ah, so you use the setCount function to update the state, and React takes care of updating the UI!

Gal Happy

Exactly! By using the useState Hook, you can manage state easily in functional components, without needing class components and their complexities!

  • Conclusion The useState Hook allows you to manage state in functional components simply and effectively. It returns a pair consisting of the current state value and a function to update it. With useState, you can make your functional components more powerful and easier to work with! 😃