Hello @rishabh_jain
Thank you for reaching out. Before answering your query, I would like to highlight the point that what you are trying to achieve, should be done through the useEffect
hook.
It is important to understand the difference between these two hooks. useContext
hook is used to send data from a component to all child components. On the other hand, useEffect
hook is used when you want to trigger something when a particular component is rendered or when you want to trigger something when a specified data is changed. Basically, useEffect
hook is used when you want to perform side effects in your components such as fetching data or directly updating the DOM.
Hence, you will need to combine useContext
hook with the useEffect
hook to achieve your desired functionality. Here is a simple example using a dummy GET API:
import React, { useState, useEffect, createContext, useContext } from 'react';
// Creating context type
const MyContext = createContext({});
// Child component that will consume the data from Provider
const ContextExample = () => {
const dummyData = useContext(MyContext);
return (
<div>
<p>userId: {dummyData.userId}</p>
<p>id: {dummyData.id}</p>
<p>title: {dummyData.title}</p>
</div>
);
};
const App = () => {
// Initially data is empty
const [data, setData] = useState('');
// We introduce side effect and get/fetch data and assign it to data variable
// We are fetching from a dummy API GET url
// It has the following key values: userId, id, title, completed
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => setData(json))
}, [data]) // [data] acts as a dependency array
// If any of the keys changes effect will take place again and data provided to Provider component will be updated accordingly
// We then pass contents of the data to the Provider component
return (
<MyContext.Provider value={{ userId: data.userId, id: data.id, title: data.title }}>
<ContextExample />
</MyContext.Provider>
);
};
export default App;
Hope this helps!