天天看點

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; 全局變量