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?