Learn how to manage application state and navigation in React apps.
Global state refers to data that needs to be accessed across multiple components in your React application. Unlike local component state, global state is not tied to a single component and can include things like themes, authentication status, or application-wide configurations.
React's Context API provides a way to share global state throughout your application without passing props through every level of the component tree. It is particularly useful for data that needs to be accessed by many components but doesn't change frequently.
// Create a theme context
const ThemeContext = React.createContext({
isDark: false,
toggleTheme: () => {},
});
// Provider component
function ThemeProvider({ children }) {
const [isDark, setIsDark] = useState(false);
const toggleTheme = () => {
setIsDark(!isDark);
};
return (
<ThemeContext.Provider value={{ isDark, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
// Consumer component
function ThemedButton() {
const { isDark, toggleTheme } = useContext(ThemeContext);
return (
<button
onClick={toggleTheme}
style={{ backgroundColor: isDark ? 'black' : 'white' }}
>
Toggle Theme
</button>
);
When using the Context API, it's important to remember that changes to context values will cause all consuming components to re-render. To prevent unnecessary re-renders, consider using React.memo or useMemo for components that consume context.
Global state management is a critical concept in React applications, allowing you to maintain and update data across multiple components. In this chapter, we'll explore Redux and its modern alternative Redux Toolkit, while also introducing simpler solutions like Zustand, Recoil, and Jotai.
Redux Toolkit simplifies state management with a modern approach:
import { configureStore } from '@reduxjs/toolkit';
const store = configureStore({
reducer: {
counter: counterSlice.reducer,
user: userSlice.reducer
}
});
export const incrementAsync = (amount = 1) => {
return async (dispatch) => {
dispatch(incrementByAmount(amount));
};
};
While Redux is powerful, it might be overkill for simpler applications. Consider these alternatives:
const count = useAtom(counterAtom);
function Component() {
const [count, setCount] = useAtom(counterAtom);
return <div>{count}</div>;
}
Question 1 of 9