Import
import { useState } from 'react';
Declare State
const [state, setState] = useState(initialValue);
state
: The current state value (can be any type: number, string, object, array, etc.).setState
: A function to update state
; calling it triggers a re-render.initialValue
: The initial state, or a function returning the initial state.Example
function Example() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>Current count: {count}</p>
<button onClick={handleClick}>Increase</button>
</div>
);
}
Counter or Simple Numeric State
const [count, setCount] = useState(0);
Form Inputs
const [inputValue, setInputValue] = useState('');
function handleChange(e) {
setInputValue(e.target.value);
}
Boolean Toggles
const [isOpen, setIsOpen] = useState(false);
function toggleOpen() {
setIsOpen(!isOpen);
}
Managing Arrays
const [list, setList] = useState([]);
// To add an item to the array
setList(prevList => [...prevList, newItem]);
Managing Objects