This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

In this article, I briefly summarized the basic usage of Hooks in the project and the use of useReducer. This time, I will look at the useContext, using these two Hooks to do a simple state management

Preknowledge context

When is context used?

React is A one-way data flow. If there are nested reference relationships between components, such as A reference to B and B reference to C, the relationship is like A doll. Without state management, it can only be transmitted layer by layer through props. React provides an API context to mitigate this situation, enabling direct transfer of values from component A to component C without passing through intermediate components.

Talk is cheap, show your code

Take a little chestnut 🌰

Three components A>B>C are nested layer by layer. Each component contains half A sentence. Component A contains my personal information, which needs to be displayed in component C and requires information data not to be transmitted through component B.

Here’s the implementation using context.

// A import React from "React "; import B from "./B"; export const nameContext = React.createContext(""); Export default function App() {return (< namecontext.provider value={"ys"}> hello, <B /> </ namecontext.provider >); }Copy the code
// component B import C from "./C"; Export default function B() {return (<C /> </>); }Copy the code
// install C import React from "React "; import { nameContext } from "./App"; Export default function C() {return (< namecontext.consumer > {(name) => <span> </span>} </ namecontext.consumer > ); }Copy the code

There are only three steps to remember to implement a context like this across component value passing (like putting an elephant in a refrigerator 🤦🏻♀️)

  1. Create a context using createContext in the component to pass the data, and export it
  2. The pass data component wraps the child component with Provide and passes the data with the value attribute
  3. The context defined by the component importing the data is received using Consumer, which is a function. (Consumption component)

Something worth knowing

  • When you create a Context object and render the component that subscribes to it in React (component B in this case), it gets the value of the nearest Provider in the component tree. The initial value passed during creation takes effect when there is no match for the Provider. The initial value does not take effect if the value of value is undefined.
  • Neither the Provider nor its internal consumer components are subject to thisshouldComponentUpdateFunction, so that the consumer component can update even if its ancestor component exits the update.
  • Changes are determined by detecting old and new values, using the same algorithm as object.is.
  • A Provider can be associated with multiple consumer components. Multiple providers can also be nested, with the inner layer overwriting the data in the outer layer

Multiple Context

Now not only do I need to convey my personal information, but I also need to display the topic I share in COMPONENT C, so I define A context in component A and receive it in component C

// A import React from "React "; import B from "./B"; export const nameContext = React.createContext(""); export const titleContext = React.createContext(""); Export default function App() {return (< namecontext.provider value={" I am ys, "}> < titlecontext.provider value={" Today's topic is Hooks using "}> Hello, <B /> </ titlecontext.provider > </ namecontext.provider >); }Copy the code
// install C import React from "React "; import { nameContext, titleContext } from "./App"; export default function C() { return ( <nameContext.Consumer> {(name) => ( <> <span>{name}</span> <titleContext.Consumer> {(title) => <span>{title}</span>} </titleContext.Consumer> </> )} </nameContext.Consumer> ); }Copy the code

Problem: When passing multiple contexts, layer upon layer of nesting becomes more complicated. This code can now be modified using the Hooks of useContext

useContext

To modify the code, we just need to change the way the consuming component (that is, the C component) gets the value and use useContext to get the value passed by the A component

import React, { useContext } from "react" import { nameContext, titleContext } from "./App" export default function C() { const name = useContext(nameContext) const title = UseContext (titleContext) return (<span> {name} {title} (useContext mode) </span>)}Copy the code

Using uesContext is another three ancestral steps

  1. import useContext
  2. Import the context object
  3. Call useContext and pass in the Context object, whose return value is the shared data

conclusion

Points worth remembering

  • useContextIs to receive acontextObject and returns thatcontextThe current value of. The currentcontextThe current value of. The currentcontextValue from the upper component that is closest to the current component<MyContext.Provider>value propDecision.
  • When the component is closest to the upper layer<MyContext.Provider>Update when theHookWill trigger a rerender and use the latest pass toprovidercontext valueValue.