Mark As Completed Discussion

Overview

The useState Hook is one of the most commonly used React Hooks. It allows us to manage state in functional components. This is particularly useful when working with functional components because, unlike class components, functional components didn't have a built-in way to manage state before the introduction of Hooks.

State and Hooks

In React, state represents the data that drives the UI. It can be thought of as the current snapshot of the component's data. State is typically updated in response to user interactions or other events.

With the useState Hook, we can define state variables and update them using a function provided by the Hook. The function for updating the state will also trigger a re-render of the component, reflecting the new state in the UI.

Let's take an example to see how to use the useState Hook:

JAVASCRIPT
1import React, { useState } from 'react';
2
3const Counter = () => {
4  const [count, setCount] = useState(0);
5
6  const increment = () => {
7    setCount(count + 1);
8  };
9
10  const decrement = () => {
11    setCount(count - 1);
12  };
13
14  return (
15    <div>
16      <h2>Counter: {count}</h2>
17      <button onClick={increment}>Increment</button>
18      <button onClick={decrement}>Decrement</button>
19    </div>
20  );
21};