State management in React refers to the management of data within a React application. React components can have local state managed by the component itself or utilize global state management solutions to share state between multiple components.
Here are some common approaches to state management in React:
1. Component State (useState hook):
– React provides the `useState` hook to manage state within functional components.
– This hook allows you to declare state variables and update them using setter functions.
– State changes are local to the component where they are declared.
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
2. Context API (useContext hook):
– The Context API allows you to pass data through the component tree without having to pass props down manually at every level.
– It’s useful for providing global data that can be accessed by multiple components.
– The `useContext` hook is used to consume the context within functional components.
Example:
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const { theme, setTheme } = useContext(ThemeContext);
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return (
<div>
<button onClick={toggleTheme}>Toggle Theme</button>
<p>Current Theme: {theme}</p>
</div>
);
}
3. Redux:
– Redux is a predictable state container for JavaScript apps, which can be used with React (though it’s not specific to React).
– It provides a global store to manage application state, and state changes are made using actions and reducers.
– Redux is suitable for large-scale applications with complex state management requirements.
Example:
const increment = () => ({ type: 'INCREMENT' });
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
default:
return state;
}
};
import { createStore } from 'redux';
const store = createStore(counterReducer);
// React Component
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state);
const dispatch = useDispatch();
const increment = () => {
dispatch(increment());
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
These are some of the most commonly used approaches to state management in React. The choice of which approach to use depends on the specific requirements of your application, the complexity of the state to be managed, and personal/team preferences.