React Component Contexts

Sometimes when creating a SPA with React, you realize you need some global variables. The easiest way to make values available at all levels of a complex ReactJS application is to use a Context. The following is an example of creating a React SPA with a single global context that shares values at all levels of the component tree. I give two examples of using the context. One is a class based React Component and the other is a function based React Component.

Two React Components using one global context.
Two React Components using one global context.

I used npx  to run create-react-app . Then I added contexts and components folders and the following files to my React src folder.

React source directory for Context example
React source directory for Context example

Here is the code I added.

MyContext.jsx … First you need a context.

MyContextProvider.jsx … I have a Consumer defined at the bottom, but am not using it. I expose one variable and one function through the context. This is just so you have an example of doing either.

index.js … Once you have a context provider exported with something in the context to use, make it global by adding it to the index.js file

MyClassComponent.jsx … This is an example of accessing the global context from a class component in React.

MyFunctionalComponent.jsx … This is an example of accessing the global context from a function component in React.

App.js … The two components could be used at any level of the tree, but I added them to App for simplicity of this example.

That’s it. You have two Components using a global context.