what is useState ?
useState is a special function in React that allows functional components to use and manage state. Before hooks were introduced, state management was exclusive to class components, but with hooks, functional components can also keep track of their own state.
Basic Syntax
import React, { useState } from 'react';
function ExampleComponent() {
// Declare a state variable named "count" with an initial value of 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
{/* Clicking the button triggers an update to the state */}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useState(0) – we are setting our Default State as 0
count – It is our state variable.
setCount – is the function we use to update it.
Updating State
It’s important to understand that state updates are asynchronous. If the new state depends on the previous state, it’s a good practice to use the functional form of the state update function.
// Correct way (using the functional form) setCount(prevCount => prevCount + 1);
Conclusion
Understanding the useState will allows you to bring state management to your functional components.