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.


This free site is ad-supported. Learn more