The new React Context API is amazing, however I seem to be always hacking my way around accessing it outside of a React component.. When you are inside a React function component or a React class component everything is great, however when you need to read or reset a value from the context (for example due to an async operation that happens in a fetch function) there is no easy way to do it..
So, is there a way to access the values in React Context Consumer outside a react component?
Later edit: I have inherited a Redux based project and slowly transition out of it. In the action creators, I have a logout function that purges the contents of the store:
export const logoutRequest = () => dispatch => {
navigate('Welcome')
// Reset apollo data
client.resetStore()
persistor.purge()
// Reset context api data HERE
//
}
I could easily create a consumer in the component that calls the logout request, but that happens in 3 different components and I wouldn't want to duplicate the code there..
To access a React context outside of the render function, we can use the useContext hook. We create the UserContext by calling the React. createContext method with a default context value. Then in the Users component, we call the useContext hook with UserContext to accxess the current value of UserContext .
One of the best and most overlooked alternatives to Redux is to use React's own built-in Context API.
You will eventually call logoutRequest()
in a component right? If you don't want to duplicate code you could create a custom hook:
const useLogout = () => {
const resetContext = React.useContext(SomeContext);
const logoutRequest = () => dispatch => {
navigate('Welcome');
client.resetStore();
persistor.purge();
resetContext();
};
return logoutRequest;
}
Then you can call const logoutRequest = useLogout()
in your component.
You can do similar thing for asynchronous operations too.
React context is available only when the UI is available. This means that on background tasks you can't access it. But that doesn't mean that you can't access it "outside" of components.
I'll give an example where you can and can't use it outside a component:
A deeper explanation for background states:
You should separate between 3 background states
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With