Context API in react with example

 

React Context API Example

The React Context API is a way to share values or state across the component tree without having to pass props manually through every level of the tree. It is useful for managing global state, such as user authentication status, theme preferences, language settings, etc.

In this example, we'll build a simple Theme Context that allows the user to toggle between light and dark themes. We will use the Context API to manage the theme and make it accessible to all components in the app.

Steps:

  1. Create a Context
  2. Provide the Context to the Component Tree
  3. Consume the Context in Components

1. Creating the Theme Context

First, let's create a file called ThemeContext.js to define and manage the context.

ThemeContext.js

javascript
// src/context/ThemeContext.js import React, { createContext, useState, useContext } from 'react'; // Create a Context for the theme const ThemeContext = createContext(); // Create a provider component to wrap the app export const ThemeProvider = ({ children }) => { // State to store the current theme (light or dark) const [theme, setTheme] = useState('light'); // Toggle theme between light and dark const toggleTheme = () => { setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light')); }; return ( <ThemeContext.Provider value={{ theme, toggleTheme }}> {children} </ThemeContext.Provider> ); }; // Custom hook to use the ThemeContext export const useTheme = () => { return useContext(ThemeContext); };

Explanation:

  • ThemeContext: This is the context we create to hold the state of the theme.
  • ThemeProvider: A component that wraps the entire app or the part of the app that needs access to the theme context. It provides the theme state and toggleTheme function to the components that need it.
  • useTheme: A custom hook that simplifies access to the context value (theme and toggleTheme).

2. Wrapping the App with the ThemeProvider

Now, we need to wrap our entire application (or parts of it) with the ThemeProvider to give all child components access to the theme context.

App.js

javascript
// src/App.js import React from 'react'; import { ThemeProvider } from './context/ThemeContext'; // Import ThemeProvider import ThemeToggle from './components/ThemeToggle'; import ThemedComponent from './components/ThemedComponent'; function App() { return ( <ThemeProvider> <div> <h1>React Context API Example</h1> <ThemeToggle /> {/* Component to toggle theme */} <ThemedComponent /> {/* Component to show current theme */} </div> </ThemeProvider> ); } export default App;

Explanation:

  • The App component is wrapped with the ThemeProvider, which makes the theme state available to all child components (ThemeToggle and ThemedComponent).

3. Consuming the Context in Components

ThemeToggle.js

This component will allow the user to toggle between light and dark themes.

javascript
// src/components/ThemeToggle.js import React from 'react'; import { useTheme } from '../context/ThemeContext'; // Import the custom hook const ThemeToggle = () => { const { theme, toggleTheme } = useTheme(); // Access the theme and toggle function from context return ( <div> <button onClick={toggleTheme}> Switch to {theme === 'light' ? 'Dark' : 'Light'} Mode </button> </div> ); }; export default ThemeToggle;

ThemedComponent.js

This component will display the current theme.

javascript
// src/components/ThemedComponent.js import React from 'react'; import { useTheme } from '../context/ThemeContext'; // Import the custom hook const ThemedComponent = () => { const { theme } = useTheme(); // Access the current theme from context return ( <div style={{ padding: '20px', marginTop: '20px', border: '1px solid #ccc' }}> <h2>Current Theme: {theme === 'light' ? 'Light' : 'Dark'}</h2> <div style={{ backgroundColor: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff', padding: '10px', borderRadius: '5px', }} > This component's theme will change based on the context value. </div> </div> ); }; export default ThemedComponent;

Explanation:

  • ThemeToggle: This component uses the useTheme hook to get the current theme and a toggleTheme function. It renders a button that toggles the theme when clicked.
  • ThemedComponent: This component also uses the useTheme hook to access the current theme and applies conditional styles (light or dark) based on the theme value.

4. Styling Based on Theme

The styling of ThemedComponent is based on the theme value provided by the ThemeContext. It uses inline styles to change the background color and text color depending on whether the theme is light or dark.

For light mode, the background is white and the text is black, while for dark mode, the background is dark gray and the text is white.


Full Project Structure

css
src/ ├── components/ │ ├── ThemedComponent.js │ └── ThemeToggle.js ├── context/ │ └── ThemeContext.js ├── App.js └── index.js

5. Final Notes

  • Context Providers: By wrapping the component tree in the ThemeProvider, any component in the tree can consume the theme context, making it very easy to manage global states like themes, user authentication, or language settings.
  • Custom Hooks: The useTheme custom hook simplifies the process of accessing context in any component.
  • Global State: The Context API provides a way to manage and share global state without the need for prop drilling (passing props down manually at each level).

This simple example demonstrates how you can use React's Context API to manage and share a global state (like theme preference) across your application. You can extend this pattern to other global states such as user authentication, language settings, and more.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

oAuth in angular