天天看点

reactjs —— useContext :上下文 & 属性之间的传递 & 全局变量

useContext

We use the ​<code>​useContext​</code>​ hook for passing values to deeply nested components. This is essentially dependency injection.

We frequently use contexts for values which will be used throughout our app, such as theme constants or localized strings.

Suppose we want to use a theme throughout our app.

Without a context, we have to pass the theme as a prop into every component - even those that don't use it! That's both a hassle and may cause unnecessary rerendering.

reactjs —— useContext :上下文 &amp; 属性之间的传递 &amp; 全局变量

  

With a context, the component that actually wants to use the theme can access it directly from the context.

reactjs —— useContext :上下文 &amp; 属性之间的传递 &amp; 全局变量