I was trying to use React's context and I faced the following issues. I am new to react, so bear with me and would appreciate if you can direct me to a useful resource
- Does a component has to be wrapped inside of a provider to be able to access the values of the context? like will the following childComponent be able to access the context even if it's not wrapped inside of a provider like
<ParentComponentProvider>
<ChildComponent />
</ParentComponentProvider>
import React, { createContext, useContext } from 'react';
const MyContext = createContext();
const ParentComponentProvider = ({ children }) => {
return (
<MyContext.Provider value="Hello from context">
{children}
</MyContext.Provider>
);
};
const ChildComponent = () => {
const contextValue = useContext(MyContext);
return <div>{contextValue}</div>;
};
const App = () => {
return (
<div>
<ChildComponent />
</div>
);
};
- if it's possible to access the context values without being direclty wrapped inside of the provider, then what is the point of wrapping a component or components inside of a provider wrapper?
- Does a change in a value of a context affect the components that are wrapped inside of a provider to re-render? what if I don't wrap the components that use the contextvalues inside of a provider, will they re-render?
To access the
valuepassed to<MyContext.Provder>, yesYou would only be able to access any default context values, ie the value you pass to
createContext()...If those components use the context via the
useContext()hook, then yes; the hook triggers a re-render when changes are detected.If there are wrapped components that do not use the hook, they will not. This is why it's generally ok to wrap your entire application in a context provider
No. Again, they will only be able to access the default context value which is not changing.
Consider the following context and provider
<MyContextProvider>will only see "Default context value"setValue()with a new value, it and the other wrapped consumers will re-render and see the new value.Here's a more involved demo showing what happens
with a top-level like this
You would see on initial render
On clicking the button, you would then see