19 Feb 2024
In React.js, the useContext hook is a built-in hook that allows functional components to consume values from the Context API. The Context API provides a way to share values, such as global state, between components without passing props through every level of the component tree manually.
Basic syntax of the useContext hook:
Step 1: Creating a Context
In this step, we create a context using React.createContext(). This creates a context object that components can subscribe to.
// Context.js
import React from 'react';
const MyContext = React.createContext();
export default MyContext;
Step 2: Creating a Provider Component
Here, we create a provider component that wraps around the part of the component tree where we want to make the context available.
// MyProvider.js
import React from 'react';
import MyContext from './Context';
function MyProvider({ children }) {
const sharedValue = 'Hello from Context!';
return (
<MyContext.Provider value={sharedValue}>
{children}
</MyContext.Provider>
);
}
export default MyProvider;
Step 3: Consuming the Context
We consume the context in components that need access to the shared data by using the useContext hook.
// MyConsumer.js
import React, { useContext } from 'react';
import MyContext from './Context';
function MyConsumer() {
const contextValue = useContext(MyContext);
return <div>{contextValue}</div>;
}
export default MyConsumer;
Step 4: Using the Provider and Consumer in the App
Finally, we integrate the provider and consumer components into our app's component tree.
// App.js
import React from 'react';
import MyProvider from './MyProvider';
import MyConsumer from './MyConsumer';
function App() {
return (
<MyProvider>
<MyConsumer />
</MyProvider>
);
}
export default App;
In this example, the MyProvider component wraps around the MyConsumer component in the App component, ensuring that the context provided by MyProvider is accessible to MyConsumer and its descendants.
In this example:
Key points of useContext Hook in react js
-
Context Creation:
- First, you need to create a context using the
createContextfunction. This function returns a context object, which consists of aProviderand aConsumer. - Example:
const MyContext = createContext();
- First, you need to create a context using the
-
Context Provider:
- Use the
Providercomponent to wrap the part of the component tree where you want to make the context available. - The
valueprop of theProvidersets the value that will be consumed by the components within its scope. - Example:
const MyComponent = () => { return ( <MyContext.Provider value={/* someValue */}> {/* Components within this scope can access the context */} </MyContext.Provider> ); };
- Use the
-
useContext Hook:
- The
useContextHook allows a functional component to subscribe to a React context. - It takes the context object as an argument and returns the current context value.
- Example:
const MyComponent = () => { const contextValue = useContext(MyContext); // Now, contextValue contains the current value of the context };
- The
-
Dynamic Context Values:
- Context values can be dynamic and may depend on the state or props of the component.
- Example:
const MyComponent = () => { const [value, setValue] = useState(/* someInitialValue */); return ( <MyContext.Provider value={value}> {/* Components within this scope can access the dynamic context value */} </MyContext.Provider> ); };
-
Nested Contexts:
- You can nest context providers to create a hierarchy of contexts. Components can then consume the context values at different levels.
- Example:
const OuterContext = createContext(); const InnerContext = createContext(); const MyComponent = () => { return ( <OuterContext.Provider value={/* outerValue */}> <InnerContext.Provider value={/* innerValue */}> {/* Components within this scope can access both context values */} </InnerContext.Provider> </OuterContext.Provider> ); };
-
Default Values:
- You can provide a default value when creating a context, and it will be used when a component is not wrapped within a
Provider. - Example:
const MyContext = createContext(/* defaultValue */);
- You can provide a default value when creating a context, and it will be used when a component is not wrapped within a
-
Context with Reducers:
- You can use the Context API along with
useReducerfor managing more complex state logic in your application. - Example:
const MyContext = createContext(); const MyComponent = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <MyContext.Provider value={{ state, dispatch }}> {/* Components can access state and dispatch using useContext */} </MyContext.Provider> ); };
- You can use the Context API along with
-
Dynamic Context in Function Components:
useContextis particularly useful for dynamically changing context values in functional components.- Example:
const MyComponent = () => { const [theme, setTheme] = useState('light'); return ( <ThemeContext.Provider value={{ theme, setTheme }}> {/* Components can dynamically access and update the theme */} </ThemeContext.Provider> ); };
-
Context in Class Components:
- While
useContextis designed for functional components, you can still use theConsumercomponent or thethis.contextproperty in class components to consume context. - Example:
class MyClassComponent extends React.Component { static contextType = MyContext; render() { const { value } = this.context; // Render based on the context value } }
- While
-
Dynamic Context Changes and Re-renders:
- Changes to the context value will trigger re-renders in components that consume the context using
useContext. - Example:
const MyComponent = () => { const [count, setCount] = useState(0); return ( <MyContext.Provider value={count}> <ChildComponent /> <button onClick={() => setCount(count + 1)}>Increment</button> </MyContext.Provider> ); };
- Changes to the context value will trigger re-renders in components that consume the context using