React Js - Context API with example
- Get link
- X
- Other Apps
React Js - Context API with example
Context API is a feature in React that allows data to be shared between components without the need to pass it down manually as props. It provides a way to share state data between components that are not directly related to each other in the component tree.
Here's an example of how to use Context API in a React app:
First, create a new context by using the createContext method:
import { createContext } from 'react'; const MyContext = createContext();
This creates a new context called MyContext.
Next, create a provider component that will provide the data to other components:
import { useState } from 'react'; import { MyContext } from './MyContext'; function MyProvider(props) { const [data, setData] = useState(''); return ( <MyContext.Provider value={{ data, setData }}> {props.children} </MyContext.Provider> ); }
In this example, the provider component sets up the state data and provides it to other components through the value prop.
Finally, use the useContext hook to access the data in a consuming component:
import { useContext } from 'react'; import { MyContext } from './MyContext'; function MyComponent() { const { data, setData } = useContext(MyContext); function handleClick() { setData('New data'); } return ( <div> <p>{data}</p> <button onClick={handleClick}>Change data</button> </div> ); }
In this example, the provider component sets up the state data and provides it to other components through the value prop.
Finally, use the useContext hook to access the data in a consuming component:
import { useContext } from 'react'; import { MyContext } from './MyContext'; function MyComponent() { const { data, setData } = useContext(MyContext); function handleClick() { setData('New data'); } return ( <div> <p>{data}</p> <button onClick={handleClick}>Change data</button> </div> ); }
In this component, the useContext hook is used to access the data and the setData function from the context. The handleClick function updates the data when the button is clicked.
By using Context API, the data can be easily shared between components without the need to pass it down manually as props.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments