current position:Home>Simple introduction to react -- the use of usecontext in common hooks

Simple introduction to react -- the use of usecontext in common hooks

2022-01-27 01:06:43 Poker_ Xu

Preface :
If before reading this article , You are right about context API If you know better , The hook There will be more advanced syntax than this

1、 Import :

The hook Still from react Just import from the package , There is no need to import... From a third-party package
 Insert picture description here

2、 Use :

We prepare three components in advance

  • The root component :< App / >
  • Child components :< Son />
  • Grandson components :< GrandSon />

The root component : Insert picture description here
Child components :
 Insert picture description here

Grandson components :
 Insert picture description here
Page effects :
 Insert picture description here
Observation found that , You can also get the value passed from the root component

summary :

If you were before that , To the original context Of API Familiar words , You can take useContext as class In the component static contextType = MyContext perhaps <MyContext.Consumer>. But why not just use the original context Well , It mainly includes the following :

  • Previous context Is from the root component , Pass through a series of components in the middle , but useContext But not , It can be passed directly across components
  • pre-use context Components , How to say that the middle component uses such as shouldComponentUpdate To organize re rendering , It is possible that the data cannot be transferred to the lower components

Called useContext The components of context Re render when value changes . If the re rendering component is expensive , You can By using memoization To optimize .

copyright notice
author[Poker_ Xu],Please bring the original link to reprint, thank you.

Random recommended