Flat Preloader Icon

Using Context to Manage State

In React, managing state efficiently is crucial for building dynamic and responsive applications. One powerful tool for managing state across a React application is the Context API. Here’s an overview of how to use Context to manage state in React:

1. Create a Context

First, you need to create a context. This can be done using the createContext method provided by React.
				
					import React, { createContext } from 'react';

export const MyContext = createContext();

				
			

2. Create a Provider Component

Next, you create a provider component that will wrap around the parts of your application that need access to the context. This provider component will hold the state and provide it to its children.
				
					import React, { useState } from 'react';

export const MyProvider = ({ children }) => {
  const [state, setState] = useState(initialState);

  return (
    <MyContext.Provider value={{ state, setState }}>
      {children}
    </MyContext.Provider>
  );
};

				
			

3. Wrap Your Application with the Provider

To make the context available throughout your application, wrap your main component (or a higher-level component) with the provider.
				
					import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { MyProvider } from './MyProvider';

ReactDOM.render(
  <MyProvider>
    <App />
  </MyProvider>,
  document.getElementById('root')
);

				
			

4. Consume the Context in Components

To access the context in any component, use the useContext hook.
				
					import React, { useContext } from 'react';
import { MyContext } from './MyContext';

const MyComponent = () => {
  const { state, setState } = useContext(MyContext);

  return (
    <div>
      <p>{state.someValue}</p>
      <button onClick={() => setState({ ...state, someValue: 'New Value' })}>
        Change Value
      </button>
    </div>
  );
};

				
			

Example: Managing User Authentication

Create the Auth Context

				
					import React, { createContext, useState } from 'react';

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  const login = (userData) => setUser(userData);
  const logout = () => setUser(null);

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

				
			

Wrap Your Application with the Auth Provider

				
					import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { AuthProvider } from './AuthContext';

ReactDOM.render(
  <AuthProvider>
    <App />
  </AuthProvider>,
  document.getElementById('root')
);

				
			

Consume the Auth Context in Components

				
					import React, { useContext } from 'react';
import { AuthContext } from './AuthContext';

const Navbar = () => {
  const { user, logout } = useContext(AuthContext);

  return (
    <nav>
      {user ? (
        <>
          <span>{user.name}</span>
          <button onClick={logout}>Logout</button>
        </>
      ) : (
        <span>Please login</span>
      )}
    </nav>
  );
};

export default Navbar;

				
			
With these steps, you can manage state across your React application efficiently using the Context API. This method is particularly useful for managing global state, such as user authentication, theme settings, or language preferences.