How to use context in React
Blog React Context Api

In this post we are going to learn what is context and how to use context in React. Context is a good way to manage global shared data between the components without using props.

What is context

Context provides a way to pass data to component tree without manually writing props at everywhere component and there can be some cases where you are using a value let’s assume theme and you are using it in several components and for that case you manually need to pass the theme prop to every component. Which maybe troublesome sometimes. So, avoid that props drilling problem Context is introduced.

When to use context

Context should only be used when we have some global shared data which is used by many components. Like current user details, token, theme , current language and many more.

How to use context in React

The context api is divided into 5 simple parts.

  • React.createContext
  • Context.Provider
  • class.contextType
  • Context.consumer
  • Context.displayName

React.createContext

This will creates a simple context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.

const MyContext = React.createContext(defaultValue);

Context.Provider

So every Context object have Provider component which is used to wrap top most component in your app. It receives a value prop which is used by our app and we can store anything in this value prop like our theme, language, current user and many more.

<MyContext.Provider value={{theme:"dark"}}>

Class.contextType

Every component which is going to use our shared data required to link with Context. So, to link component with context we uses contextType key and assign our context to our component.

MyClass.contextType = MyContext;

To access context value you can use this.context to access it.

Context.Consumer

This Consume syntax is mainly use for functional components.

<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>

Context.displayName

Context object accepts a displayName string property and React DevTools uses this string to determine what to display for the context.

const MyContext = React.createContext(/* some value */);
MyContext.displayName = 'MyDisplayName';

Example:-

import React from 'react'
import {render} from 'react-dom'

const ThemeContext = React.createContext('light')
class ThemeProvider extends React.Component {
  state = {theme: 'light'}
  toggleTheme = () => {
    this.setState(({theme}) => ({
      theme: theme === 'light' ? 'dark' : 'light',
    }))
  }
  render() {
    return (
      <ThemeContext.Provider value={this.state.theme}>
        <button onClick={this.toggleTheme}>toggle theme</button>
        {this.props.children}
      </ThemeContext.Provider>
    )
  }
}
// only doing this to shield end-users from the
// implementation detail of "context"
const ThemeConsumer = ThemeContext.Consumer

const styles = {
  dark: {
    backgroundColor: 'black',
    color: 'white',
  },
  light: {
    backgroundColor: 'white',
    color: 'black',
  },
}

class App extends React.Component {
  render() {
    return (
      <ThemeProvider>
        <ThemeConsumer>
          {theme => <div style={styles[theme]}>{theme}</div>}
        </ThemeConsumer>
      </ThemeProvider>
    )
  }
}

render(<App />, document.getElementById('root'))
Edit Example of React's new context API

If you want to learn how to forward refs to child in React you must checkout this article.

Ref

Categories: Reactjs

3 Comments

Advanced concepts that you should know in React - Blog React · February 14, 2020 at 3:49 am

[…] Context […]

How to set global variable in Reactjs - Blog React · February 24, 2020 at 3:35 am

[…] here how to use context in […]

A roadmap from beginner to advanced for React developers 2020 - Blog React · March 7, 2020 at 4:17 am

[…] Context […]

Comments are closed.