👨🏼‍💻Eugeny's Notes

React Context trap

💡TL;DR Do not use context in the context provider parent's component.

Here I want to show some issue what I faced while worked with React Context API.

// OK, let's create a context with a default context value
const Context = React.createContext({ usefulMethod: _noop });

// Then, we need a provider to provide some useful logic...
const ContextProvider = () => {
const usefulMethod = () => {
// some important functionality
};

return <Context.Provider value=>{children}</Context.Provider>
};

class App {
// a valid way to access a context within class component
contextType = Context;

componentDidMount() {
// uh oh! usefulMethod will be a default value all the time!!
// even if ContextProvider set a different value for a context value...
this.eventuallyCallThisFunction(this.context.usefulMethod);
}

eventuallyCallThisFunction() {
// something than will happen later on...
}

render() {
return (
<ContextProvider>
// your fancy React app code
</ContextProvider>
);
}

In general it's okay that React allows you to access a context's default value. That's basically why we should provide it when creating a context.

But a fact that default value will be a default value may feel counter-intuitive, because we define a context value a further on. I realized that I was deceived by context accessibility and it gave me a false feeling that later on I'll be able to use context value provided by ContextProvider.

← Home