Dynamic context in React class component

How to make a React context update dynamically on functional component tree.


Dynamic context is programing concept it is not a React feature. Dynamic context allow us update the state from deep nested components. Let’s dive into the example

We are going to use the following

  • Context Provider
  • context Consumer
  • React class components
  • Arrow function
  • Minimal React App

State

What is a state in React? State is where we kept our data, it can be simple any value, such as count, an User object, or an array of Posts etc. Remember class components have inbuilt local state management.

//App component 
 setLanguage = (language) => {
    this.setState({ language });
  };
  constructor(props) {
    super(props);
    this.state = { language: "en", setLanguage: this.setLanguage };
  }

Context

Context is simplest way to pass state through component tree in Reactjs. It requires a context and a state. A context provider allow us to initialize/update the state. In our example we use provider for initialization only, rest of the work is done with state setter function.

Language example

A language example is the simplest way to demonstrate the use of Context in React. In the App.js create the LanguageContext and inititalContext

This is class component example in which a Language context used to store and manipulate state.

Create Context

//App.js
const LanguageContext = React.createContext({
  language: "en",
  setLanguage: () => {}
});

Notice the setLanguage key, it is function placeholder for updating the state, and all component using the context get the new value.

The language state is initialized with en value, short for English.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.