Flat Preloader Icon

Context API

The Context API in React is a powerful feature that allows you to share state and other values across your application without having to pass props down manually through each level of the component tree. This can be particularly useful for global settings, themes, user information, and more.

How to Use the Context API

1. Creating a Context

First, you need to create a context using the createContext function.
				
					import React, { createContext } from 'react';

// Create a Context
const ThemeContext = createContext('light');

				
			

2. Providing a Context

To make the context available to components, wrap the part of your component tree that needs access to the context with the Provider component of the context. The Provider component takes a value prop, which will be passed to the consuming components.
				
					import React, { useState } from 'react';

const ThemeContext = createContext('light');

function App() {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={theme}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

				
			

3. Consuming a Context

To use the context value in a component, you can use the useContext hook.
				
					import React, { useContext } from 'react';

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button style={{ background: theme === 'dark' ? '#333' : '#FFF' }}>I am styled by theme context!</button>;
}

				
			

4. Updating Context Values

If you need to update the context value, you can do so from a component wrapped by the Provider. It’s common to manage the state in a parent component and provide both the state and the function to update it via context.
				
					import React, { useState, useContext } from 'react';

const ThemeContext = createContext();

function App() {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const { theme, toggleTheme } = useContext(ThemeContext);
  return (
    <button
      style={{ background: theme === 'dark' ? '#333' : '#FFF', color: theme === 'dark' ? '#FFF' : '#000' }}
      onClick={toggleTheme}
    >
      Toggle Theme
    </button>
  );
}

				
			
The Context API is a powerful tool for managing state and passing data through your component tree without prop drilling. It is ideal for global state, such as themes, user authentication, and settings. By creating a context, providing it to your components, and consuming it where needed, you can keep your code clean and maintainable.