What Is useState ?
useState is a React Hook that allows us to add and manage state in a functional component.
In simple words, useState helps us store a value and update it when needed.
For example, we can use state to store:
A counter value
User input
A selected product
A login status
Data from an API
How to Import useState
First, we need to import it from React.
import { useState } from " react " ;
Enter fullscreen mode
Exit fullscreen mode
Basic Syntax
const [ state , setState ] = useState ( initialValue );
Enter fullscreen mode
Exit fullscreen mode
Here:
state → stores the current value.
setState → updates the value.
initialValue → the starting value.
Simple Counter Example
import { useState } from " react " ;
function Counter () { const [ count , setCount ] = useState ( 0 );
function increment () { setCount ( count + 1 ); }
return ( < div > < h1 > { count } < /h1 > < button onClick = { increment } > Increase < /button > < /div > ); }
export default Counter ;
Enter fullscreen…