UseState
The useState hook is a fundamental hook in React that allows you to add state to functional components. It provides a way to declare state variables directly in a functional component and gives you a function to update those variables when they change.
Syntax
const [state, setState] = useState(initialState);
state: The current state value.setState: A function to update the state.initialState: The initial value of the state variable, which can be any data type (string, number, array, object, etc.).
Example
Here's a simple example showing how useState hook works:
Counter
import React, { useState } from 'react';
function Counter() {
// Declare a state variable named "count", initialized to 0
const [count, setCount] = useState(0);
// Function to increment the count
const increment = () => setCount(count + 1);
// Function to decrement the count
const decrement = () => setCount(count - 1);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;`
Explanation
useState(0): Initializes thecountstate variable to0.incrementanddecrement: Functions that modify thecountstate usingsetCount.- Rendering the Counter: The value of
countis displayed in an<h1>, and clicking on the buttons updates this value.
Important Notes
- Re-renders: When you call
setState, React will re-render the component with the updated state. - Functional Updates: If the new state depends on the previous state, you can pass a function to
setState:
setCount((prevCount) => prevCount + 1);
This approach is useful in cases where the state updates multiple times in a short period, ensuring each update is based on the most recent state value.