SoFunction
Updated on 2025-03-08

React Context details how to use it

1. Overview

  • Context provides a method to pass data between component trees without manually adding props to each layer of components.
  • If this value is needed in multiple components or the get value and the use value are very far apart, you can use Context to share data.
  • Such as: Regional preferences, UI themes, currently certified users, languages, etc.
  • Use with caution, which can make the component reusability worse

2. API

const MyContext = (defaultValue)
  • Create a Context object
  • Provides a default value that will only take effect if the component is in the tree that does not match the Provider.

  const MyContext = (defaultValue)
  < value={xxx}> ... </>
  • Each Context object returns a Provider React component
  • Provider receives a value attribute that is passed to the consumer component. A Provider can correspond to multiple consumer components. Multiple providers can also be used in nesting, and the inner layer will cover the outer layer of data.
  • When the value value changes, all consumer components inside it are re-rendered

class MyClass extends  {
  componentDidMount() {
    let value = ;
    /* After the component mount is completed, use the value of the MyContext component to perform some side effects */
  }
  componentDidUpdate() {
    let value = ;
    /* ... */
  }
  componentWillUnmount() {
    let value = ;
    /* ... */
  }
  render() {
    let value = ;
    /* Render based on the value of the MyContext component */
  }
}
 = MyContext;
  • The contextType property mounted on the class will be reassigned to a Context object created by ()
  • Can be accessed in any life cycle

&lt;&gt;
   {value =&gt; /* Render based on context value*/}
&lt;/&gt;
  • Use value in consumer components (subcomponents)
  • Functions are child elements; this function receives the current context value and returns a React node. The value passed to the function is equivalent to the value provided by the Provider closest to this context to the component tree. If there is no corresponding Provider, the value parameter is equivalent to the defaultValue passed to createContext().

const MyContext = ()
 = 'MyDisplayName'
&lt;&gt; //Tags displayed in DevTools:&lt;&gt;//Tags displayed in DevTools://If not  = 'MyDisplayName' ,Then display、

What to display in DevTools

III. Use

1. Custom Context (used in class components)

//
import React from 'react'
export const ThemeContext = ('light')
//
//Use where requiredimport React, { Component } from 'react';
import ThemeContext from "./context/";

class ThemedButton extends Component {
	static contextType = ThemeContext;
	render() {
		return &lt;button&gt;{}&lt;/button&gt;;
	}
}
export default ThemedButton
//
//Context package componentimport ThemeContext from './context/';
import ThemedButton from './';
import './';
function App() {
  return (
    &lt; value='dark'&gt; //dark overwrites the default value light      &lt;div className="App"&gt;
        &lt;header className="App-header"&gt;
          &lt;ThemedButton /&gt;
        &lt;/header&gt;
      &lt;/div&gt;
    &lt;/&gt;
  );
}
export default App;

2. Use Consumer support to get values ​​on multiple Contexts

Consumer can be used when multiple context values ​​are required

//
import React from 'react'
const ThemeContext = ('light')
 = 'ThemeContext'
export default ThemeContext
//
import React from 'react'
const UserContext = ('guest')
 = 'UserContext'
export default UserContext
//
//Use Provider to assign values:import React, { Component } from 'react';
import ThemeContext from './context/';
import UserContext from './context/';
import ThemedButton from './';
import './';
class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
        &lt; value={'dark'}&gt;
          &lt;div className="App"&gt;
            &lt; value={'user'}&gt;
              &lt;header className="App-header"&gt;
                &lt;ThemedButton /&gt;
              &lt;/header&gt;
            &lt;/&gt;
          &lt;/div&gt;
        &lt;/&gt;
    );
  }
}
export default App
//
import React, { Component } from 'react';
import ThemeContext from "./context/";
import UserContext from "./context/";
class ThemedButton extends Component {
	render() {
		return (
			&lt;&gt;
				&lt;&gt;
					{theme =&gt; &lt;div&gt;{theme}&lt;/div&gt;}
				&lt;/&gt;
				&lt;&gt;
					{user =&gt; &lt;div&gt;{user}&lt;/div&gt;}
				&lt;/&gt;
			&lt;/&gt;
		);
	}
}
export default ThemedButton

Use (used in functional components)

react native Hook allows functional components to use Context, and supports multiple different types of contexts

//
import React from 'react'
const ThemeContext = ('light')
 = 'ThemeContext'
export default ThemeContext
//
import React from 'react'
const UserContext = ('guest')
 = 'UserContext'
export default UserContext
//
//Use Provider to assign values:import React, { Component } from 'react';
import ThemeContext from './context/';
import UserContext from './context/';
import ThemedButton from './';
import './';
const App = () =&gt; {
  render() {
    return (
        &lt; value={'dark'}&gt;
          &lt;div className="App"&gt;
            &lt; value={'user'}&gt;
              &lt;header className="App-header"&gt;
                &lt;ThemedButton /&gt;
              &lt;/header&gt;
            &lt;/&gt;
          &lt;/div&gt;
        &lt;/&gt;
    );
  }
}
export default App
//
import { useContext } from 'react'
import ThemeContext  from './context/ThemeContext'
import UserContext from './context/UserContext'
const ThemedButton = () =&gt; {
 const theme = useContext(ThemeContext)
 const user = useContext(UserContext)
 return (
    &lt;&gt;
		&lt;div&gt;{theme}&lt;/div&gt;
		&lt;div&gt;{user}&lt;/div&gt;
	&lt;/&gt;
 )
}
export default ThemedButton

This is the end of this article about the detailed explanation of how to use React Context. For more related React Context content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!