ReactJS – Context

React’s Context API allows you to share state across your entire app (or part of it) without having to pass props down manually at every level. Here’s a detailed explanation with a good example:

What is Context?

Context provides a way to pass data through the component tree without having to pass props down manually at every level. It is often used for global settings, themes, or user data.

How to Use Context?

  1. Create a Context: Use React.createContext() to create a context.
  2. Provide a Context: Use a Provider component to pass the current context value to the tree below.
  3. Consume a Context: Use a Consumer component or the useContext hook to access the context value.

Example: Theme Context

Let’s create a simple example to demonstrate how to use context to manage theme data (light and dark mode) across an application.

Step 1: Create the Context

First, create a context for the theme.

// ThemeContext.js
import React from 'react';

const ThemeContext = React.createContext();

export default ThemeContext;

Step 2: Provide the Context

Wrap your component tree with the Provider component and pass the current theme value.

// App.js
import React, { useState } from 'react';
import ThemeContext from './ThemeContext';
import ThemedButton from './ThemedButton';

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

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

  return (
    <ThemeContext.Provider value={theme}>
      <div className={`App ${theme}`}>
        <header className="App-header">
          <h1>Welcome to the Theme Switcher</h1>
          <button onClick={toggleTheme}>Toggle Theme</button>
          <ThemedButton />
        </header>
      </div>
    </ThemeContext.Provider>
  );
}

export default App;

Step 3: Consume the Context

Now, let’s create a ThemedButton component that uses the theme context.

// ThemedButton.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';

function ThemedButton() {
  const theme = useContext(ThemeContext);
  
  return (
    <button className={`button-${theme}`}>
      I am a {theme} themed button
    </button>
  );
}

export default ThemedButton;

Step 4: Add Some Styling

Add some simple CSS to differentiate between light and dark themes.

/* App.css */
.App.light {
  background-color: white;
  color: black;
}

.App.dark {
  background-color: black;
  color: white;
}

.button-light {
  background-color: white;
  color: black;
}

.button-dark {
  background-color: black;
  color: white;
}


Tutorials Deck

TutorialsDeck is striving to provide the best learning material on technical and non-technical subjects.

Languages

Web Technologies

Database

Trending Technologies

© 2024. All rights reserved.

Contact Us @ tutorialsdeck06@gmail.com