I am just curios about if it would be possible to use the Context API inside a Context API. Like for example I would have a Context API for an AppState and want to use that in another Context API which handles a WebSocket connection?
We can now consume context with the useContext hook. Instead of using render props, we can pass the entire context object to React. useContext() to consume context at the top of our component. The benefit of the useContext hook is that it makes our components more concise and allows us to create our own custom hooks.
Conclusion. If you are in a situation where you need to implement some sort of library or widget system, then building on top of the Context API will give you most of what you need. And you also get the benefit of reduced bundle size, because it's already built into React.
The React Context API is a way for a React app to effectively produce global variables that can be passed around. This is the alternative to "prop drilling" or moving props from grandparent to child to parent, and so on. Context is also touted as an easier, lighter approach to state management using Redux.
The simple way to access the context values is by wrapping the child component in the Consumer for Class component and for the functional component we can access context with the help of useContext method of React. From there, we can access the context value as props.
This is a good scenario to use hooks instead of context.
// custom hook
function useAppState() {
//add handlers here
return appState;
}
function WebSocket() {
const appState = useAppState();
// do something (i.e reconnect) every time appState changes
useEffect(() => { /* do something */, [appState])
}
function App() {
return <WebSocket />
}
Inspired by Joseph's answer I am thinking about just using those both context api's in a custom hook together.
useMultipleContexts(){
const contextOne = useContext(ContextOne);
const contextTwo = useContext(ContextTwo);
/**
* Do something with both contexts
* in a custom hook that can be used
* multiple times with the same state
*/
}
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