React useState Hook
The useState hook allows functional components in React to store and manage data that can change over time. It is simple to use and ideal for handling basic state updates within a component.
- It lets you add state variables to functional components.
- It is best suited for simple state updates.
- The hook must be imported from React before using it.
const [state, setState] = useState(initialState)
- state: It is the value of the current state.
- setState: It is the function that is used to update the state.
- initialState: It is the initial value of the state.
Working of useState()
The useState() hook allows you to add state to functional components in React. It works by:
- Initialise State: When you call useState(initialValue), it creates a state variable and an updater function.
const [count, setCount] = useState(0);
- State is Preserved Across Renders: React remembers the state value between re-renders of the component. Each time the component renders, React keeps the latest value of count.
3. State Updates with the Updater Function: When you call setCount(newValue) React updates the state and it re-renders the component to reflect the new state value
<button onClick={() => setCount(count + 1)}>Increment</button>
Implementing the useState hook
Here is the implementation of the useState hook:
1. Counter using useState
A common example of using useState is managing the state of a counter with actions to increment and decrement the value.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
Click {count} me
</button>
);
}
Output
Reference: https://www.geeksforgeeks.org/reactjs/reactjs-usestate-hook/

Top comments (0)