`useContext` is a hook provided by React to access the value of a context. Context in React is used to share values like themes, authentication status, and other data between components without having to explicitly pass a prop through every level of the tree. Here’s a breakdown of useContext, followed by an illustrative example.
Before diving into `useContext`, it’s crucial to understand the concept of Context in React. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
// Creating a Context
const MyContext = React.createContext(defaultValue);
A Context object has two main components:
<MyContext.Provider value={/* some value */}>
2. Consumer: The `Consumer` component subscribes to context changes. However, with the advent of Hooks in React, consuming context has been made easier through the `useContext` hook, rendering the explicit use of `Consumer` less common.
`useContext` is a hook that is used to consume the context value. It accepts a context object (the value returned from `React.createContext`) and returns the current context value for that context.
Consider an application that utilizes a theme and allows the user to toggle between themes.
import React from 'react';
// Creating a context with 'light' as the default value
const ThemeContext = React.createContext('light');
function App() {
const [theme, setTheme] = React.useState('light');
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
<button onClick={() => setTheme(theme => theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</ThemeContext.Provider>
);
}
In this example, the `App` component holds the state `theme` representing the current theme and provides a button to toggle between the themes. The `ThemeContext.Provider` wraps the `Toolbar` component and the toggle button, providing the current theme to its children.
function Toolbar() {
const theme = React.useContext(ThemeContext);
return (
<div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
The theme is {theme}
</div>
);
}
Here, the `Toolbar` component uses the `useContext` hook to consume the current theme from `ThemeContext` and applies it to style the component.
`useContext` is particularly useful when:
However, useContext is not a silver bullet and may not be suitable for managing complex global state logic; in such cases, libraries like Redux or MobX may be more appropriate.
While `useContext` can be incredibly handy, it’s essential to be mindful of performance implications:
`useContext` is a powerful feature in React’s function component system, allowing for more readable, maintainable, and concise code. It solves prop-drilling issues and provides a smoother way to pass data around components. However, careful consideration is needed regarding its impact on performance and its appropriateness compared to other state management solutions.
Let's revisit our example to consider best practices and optimization.
// ThemeContext.js
import React, { createContext, useState } from 'react';
export const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
Here, `ThemeContext` and `ThemeProvider` are encapsulated in a separate module, and the toggle function is included in the context value.
// App.js
import React from 'react';
import { ThemeProvider } from './ThemeContext';
import Toolbar from './Toolbar';
function App() {
return (
<ThemeProvider>
<Toolbar />
</ThemeProvider>
);
}
The `App` component now just wraps the application with `ThemeProvider`.
// Toolbar.js
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Toolbar() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
The theme is {theme}
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
}
export default Toolbar;
The `Toolbar` component consumes the context and has access to both the current theme and the `toggleTheme` function, demonstrating the organized and efficient approach facilitated by the `useContext` hook.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here