React Context API is a way to essentially create global variables that can be passed around in a React app. This is the alternative to “prop drilling”, or passing props from grandparent to parent to child, and so on. Context is often touted as a simpler, lighter solution to using Redux for state management. I haven’t used Redux myself yet, but every time I use React’s Context API, I have to look it up because it doesn’t seem obvious to me.

I’m going to leave some brief, concise steps to getting started with Context here.

Prerequisite

Create Context

Imagine I have some information I want to be available anywhere or everywhere throughout a React app. A theme might be implemented using Context - for example, on this site I have Context serving three themes: dark mode, light mode, and MS-DOS mode (on the 404 page).In this simple example, I’ll use a logged in user.

I’ll create Context, and call it UserContext. This will also give me UserContext.Provider and UserContext.Consumer. What these two components do is straightforward:

  • Provider - The component that provides the value
  • Consumer - A component that is consuming the value

So I’ll create it with React.createContext() in a new file called UserContext.js.

src/UserContext.js

import React from 'react'

const UserContext = React.createContext()

export const UserProvider = UserContext.Provider
export const UserConsumer = UserContext.Consumer

export default UserContext

I’m passing in an empty object value here to represent that I might be filling in this data later with an API call. You can pre-populate this with whatever data you want, in case you’re not retrieving the data through an API.

React.createContext(true)

Providing Context

The provider always needs to exist as a wrapper around the parent element, no matter how you choose to consume the values. I’ll wrap the entire App component in the Provider. I’m just creating some value (user) and passing it down as the Provider value prop.

src/App.js

import React from 'react'
import HomePage from './HomePage'
import { UserProvider } from './UserContext'

function App() {
  const user = { name: 'Tania', loggedIn: true }

  return (
    <UserProvider value={user}>
      <HomePage />
    </UserProvider>
  )
}

Now any child, grandchild, great-grandchild, and so on will have access to user as a prop. Unfortunately, retrieving that value is slightly more involved than simply getting it like you might with this.props or this.state.

#javascript #react #hooks #classes #programming #api

Using Context API in React (Hooks and Classes)
2.35 GEEK