Having nested Contexts will not cause any issues in your code. In the above case if you subscribe to UserContext
in MenuContext
, the MenuContext
will only re-render when the UserContext
has changed the value supplied to its provider. However unless the MenuContext changes the value it passes to the MenuContext Provider
its children who are subscribing to MenuContext
will not re-render and also no other children will be re-rendered
import React from "react";
import ReactDOM from "react-dom";
import { UserProvider } from "./UserProvider";
import { ThemeProvider } from "./ThemeProvider";
import { MenusProvider } from "./MenuProvider";
import "./styles.css";
function Child() {
console.log("Child render");
return <div>Menus Child</div>;
}
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<UserProvider>
<ThemeProvider>
<MenusProvider>
<Child />
</MenusProvider>
</ThemeProvider>
</UserProvider>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can see a DEMO in the codeSandbox here
P.S. However you must make sure that you are not creating a new object
while passing the value to a Provider otherwise everytime the Provider
re-renders all children which subscribe to its context will re-render