How to use React hooks for global state management



Image not found!!

React hooks provide a convenient way to manage state in functional components. To manage global state in a React application using hooks, you can use the useContext hook in combination with the createContext API. Here's a step-by-step guide:

Step 1: Create a Context

Create a new file, let's say AppContext.js, where you'll define your context.

jsx
// AppContext.js import React, { createContext, useReducer, useContext } from 'react'; // Create the context const AppContext = createContext(); // Create a provider component export const AppProvider = ({ children }) => { const initialState = { // Your initial global state goes here // For example: user: null, theme: 'light', }; const reducer = (state, action) => { // Define your reducer logic based on different actions switch (action.type) { case 'SET_USER': return { ...state, user: action.payload }; case 'TOGGLE_THEME': return { ...state, theme: state.theme === 'light' ? 'dark' : 'light' }; default: return state; } }; const [state, dispatch] = useReducer(reducer, initialState); return ( <AppContext.Provider value={{ state, dispatch }}> {children} </AppContext.Provider> ); }; // Create a custom hook for accessing the context export const useAppContext = () => { return useContext(AppContext); };

Step 2: Wrap your App with the Provider

In your index.js or the main entry point of your app, wrap your App component with the AppProvider:

jsx
// index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { AppProvider } from './AppContext'; ReactDOM.render( <React.StrictMode> <AppProvider> <App /> </AppProvider> </React.StrictMode>, document.getElementById('root') );

Step 3: Use the Global State in Components

Now, in any component where you want to access or modify the global state, use the useAppContext hook:

jsx
// ExampleComponent.js import React from 'react'; import { useAppContext } from './AppContext'; const ExampleComponent = () => { const { state, dispatch } = useAppContext(); const setUser = (user) => { dispatch({ type: 'SET_USER', payload: user }); }; const toggleTheme = () => { dispatch({ type: 'TOGGLE_THEME' }); }; return ( <div> <p>User: {state.user}</p> <button onClick={() => setUser('John')}>Set User</button> <p>Theme: {state.theme}</p> <button onClick={toggleTheme}>Toggle Theme</button> </div> ); }; export default ExampleComponent;

Now you have a global state accessible from any component using the useAppContext hook. Changes to the global state trigger re-renders in all components that use it. This setup provides a simple way to manage global state in a React application using hooks and context.