This is a demonstration of how React context can save you from prop drilling, but it can't save you from unnecessary renders. When a context provider's value is updated, it's entire descendant tree has to be re-rendered. In this regard, it is no different or better than prop-drilling.
See the hosted page or build locally.
Note: the hosted version is a production build, which naturally does not include <React.StrictMode>
. If you run locally, you will see twice as many renders because of strict mode. See the Strict Mode documentation for more information.
To improve performance, you have to move to a more modern state management solution like Jotai (demonstrated here), Zustand, Valtio, MobX or the like.
Compare the differences between:
- Prop drilling:
src/AppDrilling.jsx
- Context:
src/AppContext.jsx
- Jotai:
src/AppJotai.jsx
To run:
pnpm install
pnpm dev