DEV Community

Albert Font
Albert Font

Posted on

Understanding react context

When trying to create complex apps with react most of us end up facing an amazing utility called context. But, what is a context exactly?

As its name suggests a context is something that wraps items inside it. A real-life context could be economics, that embrace (market, stocks, money....).

Moving into some React vocabulary, we could understand the context as data that can be accessed along with all items that are wrapped inside it. Keep those bold words inside as they would be crucial when understanding exactly how to use context. A real example could be a context called user, which contains all the app user information and can be accessed along with all pages/components in the app.

Image description

Now let's see how this context is created, how we set which components will have access to it and how we can access its data. For this, we're going to follow the previous example and create a simple app that is going to have a user context with some routes inside it.

CREATING CONTEXT

To create a context we need to use a react hook called createContext(). This will turn the UserContext variable into a real context.

import { createContext, useState } from 'react'

const UserContext = createContext()
Enter fullscreen mode Exit fullscreen mode

It is important to know that now the UserContext variable, is a context, and so it has 2 important components inside of it, Provider and Consumer. They could be understood as it follows:

  • Provider: Provider is the component that will be called when exposing all user data.

  • Consumer: Consumer is the component that will be called when accessing user data.

To make it easier to work with the context I recommend creating a custom method that will return the user context. Provider along with some values inside of it that will be accessed when consuming it.

import { createContext, useState } from 'react'

const UserContext = createContext()

function UserProvider({ children }) {
  const [user, setUser] = useState({ locale: 'es', userName: 'John' })

  const setUpUser = ({ locale, userName }) => {
    setUser({ locale, userName })
  }

  return (
    <UserContext.Provider value={{ user, setUpUser }}>
      {children}
    </UserContext.Provider>
  )
}

export { UserContext, UserProvider }


Enter fullscreen mode Exit fullscreen mode

In this example, we will do a simple context that will just contain the user object. This object will let us know what locale the user wants and its user name.

If you look at the component you can see a prop called value. value is the prop that will receive all the data we want to expose inside the context. In this case, we're sending the user data and a method to set up the user.

CONSUMING THE USER CONTEXT

To consume the user context, first of all, we need to use the provider, to do this we will call the UserProvider component we created before and use it to wrap all the app inside our user context so all pages can access user data.

import React from 'react'
import ReactDOM from 'react-dom'
import { UserProvider } from './contexts/user'

ReactDOM.render(
  <React.StrictMode>
    <UserProvider>
      <App />
    </UserProvider>
  </React.StrictMode>,
  document.getElementById('root')
)

Enter fullscreen mode Exit fullscreen mode

Now, all the app has access to the user context. So let's go to app.js and consume it so the username gets rendered on screen. To do this, we will call another react hook called useContext(), and we will pass our UserContext as a parameter to let it know that we want to access that context.

import { useContext } from 'react'
import { UserContext } from '../../contexts/user'

export default function App() {
  const { user } = useContext(UserContext)
  return <h1>{user.userName}</h1>
}
Enter fullscreen mode Exit fullscreen mode

In this case, we retrieve the user from the context and we're accessing its userName property to be displayed on the screen.
The final result would be the following:

Image description

And that's how you work with a basic context, you can make it as complex as you want by creating multiple states inside it, custom functions, data manipulation, etc... But this is the basics. Hope I've helped you understand more about them!

You can follow me on my social media:

Github: https://github.com/Alverd04
Linkedin: https://www.linkedin.com/in/albert-font-fernandez/

Oldest comments (0)