What is Context API in React js ?
In React.js, the Context API is a mechanism for sharing state and functionality between components without having to explicitly pass props through the component tree. It provides a way to pass data through the component tree without having to pass props down manually at every level.
The Context API consists of two main parts:
1. React.createContext:
- This function creates a Context object. It takes an optional argument, the default value for the context. The `createContext` function returns an object with `Provider` and `Consumer` components attached to it.
jsx
const MyContext = React.createContext(defaultValue);
2. <MyContext.Provider> and <MyContext.Consumer>:
- The Provider component is used to wrap the part of the component tree where you want to make the context available. It takes a "value" prop that will be the value of the context.
- The "Consumer "component is used to access the value of the context within a component.
js
<MyContext.Provider value={/* some value */}>
{/* Components inside here can access the value */}
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
</MyContext.Provider>
Here's a simple example to illustrate the use of the Context API:
js
import React, { createContext, useContext } from 'react';
// Step 1: Create a context with a default value
const ThemeContext = createContext('light');
// Step 2: Use the context in a component
function ThemedComponent() {
const theme = useContext(ThemeContext);
return (
<div style={{ background: theme === 'light' ? '#eee' : '#222', color: theme === 'light' ? '#000' : '#fff' }}>
Current Theme: {theme}
</div>
);
}
// Step 3: Provide the context value higher up in the component tree
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedComponent />
</ThemeContext.Provider>
);
}
export default App;
In this example, the "ThemedComponent" can access the current theme without explicitly passing it as a prop through each level of the component tree. The "ThemeContext.Provider" sets the context value for its descendants.
How to Create Login Page in React js
What is Virtual DOM in React js
How to create a Table in React js
How to Upload Image in React js
How to Implement Search Functionality in React js
How to Connect React js with Node js Backend
How Many Days to Learn React js
How to Use JQuery in React js
What is Context API in React js
How to Use Chatgpt API with Python
Post a Comment