How to use React Context effectively?

React Context has been a controversial topic. For the longest time, react context API was experimental but was later made a normal element of the API. React context functional component is now easier to utilize than ever, making it easier to misuse. We’re going to go through how to use react Context effectively in this react context API tutorial. We believe you’ll find how to use react Context effectively blog concise and informative.

What is the concept of React Context?

React context authentication is conceptually similar to a wormhole component. It is intended to transfer value from a Provider to all of its distantly connected child Consumers without passing it via all of the components in between. In a nutshell, it’s a method of avoiding “prop drilling.”

How to Establish a Context?

react context API example was created with React.createContext method.

const MyContext = React.createContext()

If you’re receiving react context API without a Provider higher up the tree, you’re either making a huge error or doing everything correctly. Without intending to be insulting, it’s more probable that you’re committing an error by failing to provide a default. Value serves as a signal that an issue needs to be addressed.

Context creation returns an object with two components, Provider and Consumer. Providers are parent components that get a value prop from their Consumer offspring. Here is a little demonstration utilizing a ThemeContext:

const ThemeContext = React.createContext()

function App() {

  return (

    <ThemeContext.Provider value=”light”>

      <Header />

      <Main />

      <Footer />



function Header() {

  return (


      {theme => {

        return (



              backgroundColor: theme === ‘light’? ‘#eee’ : ‘#111’,



            <Nav />







As you can see, the Header component uses a Consumer component to consume the ThemeContext. The theme is passed directly to the Header without requiring the value to be passed as a parameter. Please forget about the Consumer element now that you’ve seen how everything works with the module and the render prop API. Eliminate it from your mind. Soon enough, we’ll demonstrate a more efficient method of consuming a react context functional component.

Now that we have a general understanding of how to construct and utilize a React Context let’s cover some of the philosophy around its effective use.

Consider the local first, then the global.

Once you’ve mastered how to use react Context effectively, it’s tempting to utilize it as a global store. While it may operate in this manner and may even be successful, we do not view it in this manner. At the very least, it is not the first notion that comes to mind when we want global data.

Contexts, in our opinion, should be associated with a specific issue and not serve as a repository for all your data. As a result, we utilized react context authentication more frequently while working on a more localized issue.

It is feasible to utilize worldwide, but you should pause before assessing whether there is a better appropriate option.

As we’ll explore shortly, if the data supplied to the value prop changes often, React Context can result in a high number of rerenders. If we utilized a react context API example at a high standard in the tree, such as a ThemeProvider, we would like to ensure that this component’s value does not frequently change to ensure the project runs smoothly.

Always save your Provider

We cannot recall a single instance over our years of coding React when there was a compelling reason for us to avoid creating a custom Provider for a context. This is how we do it:

const ThemeContext = React.createContext()

export function ThemeProvider({ children }) {

  return <ThemeContext.Provider value=”light”>{children}</ThemeContext.Provider>


What motivates us to do this? This enables us to maintain complete control over value. We do not want to provide my Provider’s users with options over which we do not have express control. We can provide them with properties that allow them to modify the ultimately set value, but we retain control. This avoids any future issues and adequately expresses the Context’s worries.

Make an API accessible.

To our mind, the purpose of building a Context is to specify precisely how you want consumers to interact with their related Providers. Another way of putting this is that if we supply Consumers with a state, we must also offer them the handlers for that state. We are strong believers in giving users of my components dedicated state updaters, such as the following:

const ThemeContext = React.createContext()

export function ThemeProvider({ children }) {

  const [theme, setTheme] = React. useState(‘light’)

  const handlers = React. useMemo(

    () => ({

      lighten: () => {



      darken: () => {



      toggle: () => {

        setTheme(s => (s === ‘light’ ? ‘dark’ : ‘light’))




  return (

    <ThemeContext.Provider value={[theme, handlers]}>





Construct a unique hook for your Context

There was a brief window of opportunity during which we needed to utilize the Context. Consumer render prop pattern exists, but we haven’t utilized it because React Hooks considerably simplified context consumption. Rather than sending the Context object back and forth into React.

Instead of using Context in every component that requires it, we export a custom hook from the same file that contains the Context, as follows:

export const useThemeContext = () => React.use context(ThemeContext)

Wrap Up

You are now equipped to optimize your React Context use. As you can see through this react context API tutorial, there are several approaches, and the one you select depends on your circumstances.

Thus, part of mastering React Contexts is gaining experience and occasionally reflecting on your code to determine whether you might have done something differently.

Leave a Reply

Your email address will not be published. Required fields are marked *