Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the React Context API inside a Context API or do I have to merge them?

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?

like image 376
thiloilg Avatar asked Oct 11 '19 08:10

thiloilg


People also ask

Can I use context inside context React?

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.

In which of the following cases is it advisable to use React context API?

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.

How does React context API work?

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.

Can I use context API in functional component?

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.


2 Answers

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 />
}
like image 184
Joseph D. Avatar answered Sep 19 '22 13:09

Joseph D.


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
   */


}

like image 37
thiloilg Avatar answered Sep 19 '22 13:09

thiloilg