π§ Understanding React State
State is a built-in object in React components used to store dynamic data that affects how a component renders and behaves. Itβs the βbrainβ of interactive UI components.
βοΈ What is useState
?
In functional components, you use the useState()
hook to declare state.
Example:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
Here, count
is a state variable. setCount
is the function used to update it.
π Rules of Using State
- You must import
useState
fromreact
. useState
returns an array: [value, setter]- You cannot directly modify the state (use the setter function).
- Setting state re-renders the component.
π§© Multiple State Variables
function Profile() { const [name, setName] = useState("Sangram"); const [age, setAge] = useState(25); return <p>{name} is {age} years old</p>; }
You can use multiple useState
hooks for different pieces of state.
β Best Practices
- Initialize state with a sensible default.
- Use one state per concern instead of nesting complex objects.
- Keep derived values outside of state.
- Update state immutably (e.g., donβt directly mutate arrays/objects).