
Usestate in ReactJS
✅ useState in ReactJS
useState
is a React Hook that allows you to add state to functional components. It provides a way to manage variables that can trigger re-renders when updated.
📌 Why Use useState
?
State Management → Helps store and update values that change over time.
Reactivity → Re-renders the component when the state changes.
Simplicity → Easy to use for managing simple UI states like form inputs, toggles, counters, etc.
📌 Syntax
<div> <div> <div> <div> import React, { useState } from 'react';const ToggleComponent = () => { const [isOn, setIsOn] = useState(false); const toggle = () => setIsOn((prev) => !prev); <div> <button onClick={toggle}>{isOn ? 'ON' : 'OFF'}</button> </div> );};export default ToggleComponent;
🛠 Explanation:
Boolean State →
useState(false)
is used to manage on/off state.Toggle Function →
!prev
flips the current state using functional updates.
📌 6. When to Use useState
?
✅ Use useState
when:
You are managing simple, local component states.
State changes are independent of other components.
You are handling user input, toggles, or counters.
❗ Avoid useState
when:
State logic is complex and involves multiple transitions → Use
useReducer
.Data needs to be shared across components → Use
useContext
or a global state.Performance optimizations are required → Consider
useMemo
oruseCallback
.
📌 7. Conclusion
useState
is the most straightforward way to manage state in React functional components.It is perfect for managing UI state such as form inputs, toggles, and dynamic content.
Combine it with other hooks like
useEffect
for side effects oruseContext
for global state management.