- 1.React context allows us to access shared state from our components without passing props
- 2.We should use context sparingly, only for state that would be painful to share through passing props
- 3.How to use
useContextto simplify syntax when using context with functional components
React context allows us to share state across our app without passing it as props. This is helpful for apps with many levels of component nesting when we would need to use the same state across multiple components and pass state as props through many levels of components (aka "prop drilling"). The React team recommends we use context sparingly because it makes component reuse more difficult.
"Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language." - React official docs on context
"...sometimes the same data needs to be accessible by many components in the tree, and at different nesting levels. Context lets you “broadcast” such data, and changes to it, to all components below. Common examples where using context might be simpler than the alternatives include managing the current locale, theme, or a data cache." - React official docs on context
Please read the following official React guide on context.
- 1.Feel free to skim through the API section on first read; the context components and functions will make more sense after reviewing the examples
- 2.Note the Dynamic Context example and how it passes
this.state.themeas the initial value to
app.js. This means whenever
app.js, all components within
ThemeContext.Providerwill re-render with the new theme. The example uses a standard callback method
app.jsto update the theme across the app.
- 3.The Updating Context from a Nested Component example stores the class method
this.stateitself, and passes
this.stateas the value of
this.toggleThemefunction is available in all components that subscribe to
ThemeContext. This removes the need for us to pass
this.toggleThemevia prop drilling.
useContextis a React Hook that allows us to retrieve the latest value of the context object passed to it. It replaces context features
Context.Consumerfrom the context guide above, and can simplify our code when using functional components. Rocket recommends using
useContextfor context when using functional components.
Please read the following official React guide on
- 1.Besides providing simpler syntax for reading context,
useContextdoes not change the use cases for context. The examples from the official guide on context still apply, albeit with different syntax.
React Hooks useContext
Please checkout the finished code in this repository, ensure that you're on the
react_contextbranch if you want to test out the application on your machine you will need to install the dependencies with the command
npm installafter the installation you can then run the application with the command