useState is a React Hook that allows functional components to manage the state internally.
With useState, functional components can now have stateful logic, making them more powerful and versatile.
Before the introduction of Hooks in React 16.8, state management was primarily associated with class components.
Always call useState at the top level of your component. Do not call it inside loops, conditions, or nested functions.
// Correct const [count, setCount] = useState(0); // Incorrect if (condition) { const [count, setCount] = useState(0); // Don't do this }
The order in which we call "useState" hooks must be consistent across renders.
This ensures that React can correctly associate state variables with their corresponding useState calls.
// import useState hook react library import React, { useState } from 'react'; const YourCounter = () => { // Declare a state variable named and update State method with an initialValue. const [stateValue, setState] = useState(0); // InitialValue return ( <div> <button onClick={() => setState(stateValue + 1)}> Increment </button> <p>Current State Value: {stateValue}</p> </div> ); }; export default YourCounter;
import React, { useState } from 'react'; const YourCounter = () => { // Declare a state variable named "count" with an initial value of 0 const [count, setCount] = useState(0); // Event handler for incrementing the count const increment = () => { setCount(count + 1); }; // Event handler for decrementing the count const decrement = () => { setCount(count - 1); }; return ( <div> <button onClick={increment}>Increment</button> <p>Count: {count}</p> <button onClick={decrement}>Decrement</button> </div> ); }; export default YourCounter;
`useState(0)` initializes the state variable count with an initial value of `0`. The `useState` function returns an array with two elements: the current state value (count) and a function (setCount) to update the state.
The `count` state is displayed within the component's JSX.
Event handlers `increment` and `decrement` use the `setCount` function to update the state, triggering a re-render of the component with the updated value.
When the new state value depends on the previous state, use the functional update form of `setCount`.
This ensures that you are working with the most up-to-date state.
// Correct const increment = () => { setCount(prevCount => prevCount + 1); }; // Incorrect const increment = () => { setCount(count + 1); // May lead to some unexpected behaviour };
Before 18.2.0v, If we have multiple `useState` functions in a block of code, then for each state update our components re-render.
To Prevent multiple re-rendering and Increase the efficiency of our application, React under the hood handle Automatic Batching, which will update all state values at once and re-render components only once.
import React, { useState } from 'react'; const YourCounter = () => { // Declare a state variable named "count" with an initial value of 0 const [cartItem, setCartItem] = useState(0); const [totalAmount, setTotalAmount] = useState(0); // Event handler for incrementing the cartItem const increaseCartItem = () => { setCartItem(cartItem + 1); setTotalAmount((cartItem + 1) * 500) }; return ( <div> <p>Cart Items: {cartItem}</p> <p>Total Amount: {totalAmount}</p> <button onClick={increaseCartItem}> +1 </button> </div> ); }; export default YourCounter;