Creating and Using Context with createContext and useContext in React JS
React's Context API provides a way to pass data through the component tree without having to pass props down manually at every level. This is particularly useful for global data such as themes, user authentication, and language preferences. In this article, we'll explore how to create and use context in React using `createContext` and `useContext`.
1. What is `createContext`?
The createContext function is used to create a context object. This object will allow you to share values across your component tree without having to manually pass props at every level. You can think of context as a container that holds values you want to be accessible throughout your app.
2. What is `useContext`?
The useContext hook allows a component to consume the context created by `createContext`. This hook provides a way for a component to subscribe to context updates, so that the component re-renders whenever the context value changes.
3. Example: Creating and Using Context with `createContext` and `useContext`
Let's look at an example where we create a simple theme context that allows us to switch between a light and dark theme.
Step 1: Creating the Context
import React, { createContext, useState } from 'react';
// Create the context with default value
const ThemeContext = createContext();
export default ThemeContext;
In the first step, we use `createContext` to create a ThemeContext. The context will hold the value of the current theme (light or dark) and a function to toggle the theme. We can now export this context for use in other components.
Step 2: Providing the Context Value
import React, { useState } from 'react';
import ThemeContext from './ThemeContext';
import ThemeToggle from './ThemeToggle';
const App = () => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
Current Theme: {theme}
);
};
export default App;
In this step, we create the App component. We define a theme state using `useState` and a function toggleTheme that switches between 'light' and 'dark' themes. The context is provided to the component tree using the ThemeContext.Provider, which wraps the components that need access to the context.
Step 3: Consuming the Context with `useContext`
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
const ThemeToggle = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
The current theme is: {theme}
);
};
export default ThemeToggle;
Now, in the ThemeToggle component, we use the useContext hook to access the theme value and the toggleTheme function from the context. Whenever the button is clicked, the theme will toggle between 'light' and 'dark', and the component will re-render with the new theme.
4. Understanding the Flow
Here's how the context flows in this example:
- The ThemeContext.Provider wraps the component tree and provides the theme and toggleTheme function.
- Any component within this tree can access the context using the useContext hook.
- In the ThemeToggle component, the theme value is consumed and displayed. The button allows toggling the theme, which triggers a state update in the parent component.
5. Advantages of Using `createContext` and `useContext`
The Context API provides several benefits:
- No Prop Drilling: You can share data across the component tree without passing props manually through each intermediate component.
- Global State Management: The Context API is an efficient way to manage global state like themes, authentication, or user preferences.
- Cleaner Code: Using context reduces the need to manage state in multiple components or pass props at every level, leading to cleaner, more maintainable code.
6. Conclusion
React's Context API, along with the createContext and useContext functions, provides a powerful and simple way to manage and share state globally across your components. It eliminates the need for prop-drilling and makes it easier to maintain and access global data like themes, user authentication status, and language settings.
Whether you're building a small or large application, the Context API can simplify your state management, improve code readability, and make your React app more scalable.