Loading...

In React, components often need to update the UI through user interactions such as typing in a form, clicking a button, switching tabs, or adding an item to a cart.
To handle these updates, components need memory to remember what changed. In React, this component-specific memory is called state.
State is like a small personal database for a component. It allows the component to store values over time and update the UI whenever the state changes. When the state updates, React re-renders the component to reflect the new UI.
React provides a built-in hook called useState to manage state inside functional components.
Step 1: Import useState
import { useState } from 'react';Step 2: Declare a State Variable
const [count, setCount] = useState(0);
// count: current value of the state
// setCount: function to update the state
// useState(0): sets initial value to 0Step 3: Use and Update State
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
You clicked {count} times
</button>
);
}When the user clicks the button, setCount updates the value of count, and React re-renders the component to show the new count.