React Hooks(三) useContext

useContext() can be used to share state between components.

Instructions

1. Introduce createContext, useContext
2. Create a handle through createContext
3. Determine the shared scope through Context.Provider
4. Distribute content through value
5. Get data through useContext(Context) in subcomponents

Now there are two components that need to share state, as follows:

<div className="test">
	<Navbar />
	<Messages />
</div>

Step 1: Use React's Context API on their parent components to create a Context outside the component

const TestContext = React.createContext({
    
    });

Step 2: TestContext.Provider provides a Context object that can be shared by subcomponents

<TestContext.Provider 
	value={
    
    {
    
    
		username: 'superawesome',
	}}
>
	<div className="test">
		<Navbar />
		<Messages />
	</div>
<TestContext.Provider/>

Step 3: Use the useContext() hook function to introduce the Context object and get the username attribute from it

const Messages = () => {
    
    
	const {
    
     username } = useContext(TestContext);
	return (
		<div className="messages">
      		<p>1 message for {
    
    username}</p>
		</div>
	)
}

All codes are as follows:

import React, {
    
     useContext, createContext } from "react";
import ReactDOM from "react-dom";

const TestContext= createContext({
    
    });

const Navbar = () => {
    
    
  const {
    
     username } = useContext(TestContext)

  return (
    <div className="navbar">
      <p>{
    
    username}</p>
    </div>
  )
}

const Messages = () => {
    
    
  const {
    
     username } = useContext(TestContext)

  return (
    <div className="messages">
      <p>1 message for {
    
    username}</p>
    </div>
  )
}

function App() {
    
    
  return (
	<TestContext.Provider 
		value={
    
    {
    
    
			username: 'superawesome',
		}}
	>
		<div className="test">
			<Navbar />
			<Messages />
		</div>
	<TestContext.Provider/>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Note:
Components that use useContext will always re-render when the context value changes, which means that useContext can read the value of the context and subscribe to changes in the context. Even if the ancestor uses React.memo or shouldComponentUpdate, it will re-render when the component itself uses useContext.
Look at an example:

import React, {
    
     useState, createContext } from "react";
import Test6 from "./Test6";
export const testContext = createContext({
    
    })

const App = () => {
    
    
  const [count, setCount] = useState(0)

  const addCount = () => {
    
    
    setCount(count+1)
  }

  return (
    <>
      <testContext.Provider value={
    
    
        {
    
    count}
      }>
        <Test6 />
      </testContext.Provider>
      <button onClick={
    
    addCount}>{
    
    count}</button>
    </>
  );
}

export default App;

Test6.js

import React, {
    
     useContext } from 'react'
import {
    
     testContext } from './App'
const Test6 = React.memo(() => {
    
    
  let {
    
    count} = useContext(testContext)
  
  return (
    <div>
      {
    
    count}
    </div>
  )
})
export default Test6

Result:
Please add a picture description
Every time the value of count is changed, the Test6 component will re-render even if it uses memo.

Guess you like

Origin blog.csdn.net/LittleMoon_lyy/article/details/124521156