State management is a core concept in React that allows components to create and manage dynamic data. State represents data that can change over time and influences what the UI renders.
useState
Hook
React provides the useState
hook to add state to functional components. It returns a pair: the current state value and a function to update it.
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div style={{ textAlign: 'center' }}> <h2>Count: {count}</h2> <button onClick={() => setCount(count + 1)} style={{ padding: '10px 20px', fontSize: '18px', backgroundColor: '#3498db', color: '#fff', border: 'none', borderRadius: '8px', cursor: 'pointer' }} >Increment</button> </div> ); }
In this example, clicking the button calls setCount
to update the state. React re-renders the component to show the updated count automatically.
Sometimes multiple components need to share state. In such cases, state is moved ("lifted") to their closest common ancestor. This allows passing the state and update functions down as props to keep components in sync.
For larger applications, managing state with only useState
can get complex. React offers the useReducer
hook for managing more intricate state logic. Additionally, external libraries like Redux, MobX, or Zustand can be used for global state management across the app.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!