Mark As Completed Discussion

Using State Hooks

In React, the useState hook is used to manage state in functional components. It allows us to add state to our functional components without converting them to class components.

To use the useState hook, we need to import it from the 'react' library:

JAVASCRIPT
1import React, { useState } from 'react';

The useState hook accepts an initial state value and returns an array with two elements:

  1. The current state value
  2. A function to update the state value

Here's an example of using the useState hook to create a counter component:

JAVASCRIPT
1function Counter() {
2  const [count, setCount] = useState(0);
3
4  const incrementCount = () => {
5    setCount(count + 1);
6  };
7
8  return (
9    <div>
10      <p>Count: {count}</p>
11      <button onClick={incrementCount}>Increment</button>
12    </div>
13  );
14}

In this example, we initialize the count state variable with an initial value of 0. The setCount function is used to update the state value when the button is clicked.

By using the useState hook, we can easily manage state in functional components and leverage the benefits of React state management without using class components.

Try implementing a simple counter using the useState hook! See if you can increment the count when the button is clicked.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment