[JS Pattern] Provider Pattern

Make data available to multiple child cpmpopnents to avoid prop drilling

Create a Context:

 

 

 

Hooks

We can create a hook to provide context to components. Instead of having to import useContext and the Context in each component, we can use a hook that returns the context we need.

function useThemeContext() {
    const theme = useContext(ThemeContext);
    
    if (!theme) {
      throw new Error("useThemeContext must be used within ThemProvider")
    }
    return theme;
}

 

Instead of wrapping the components directly with the TmemeContext.Provider component, we can create a HOC that adds returns this component with the provided values. This way, we can separate the context logic from the rendering components, which imporves the resuability of the provider.

 

 

[Note] From JS Patterns Book

 

posted @ 2022-01-23 16:46  Zhentiw  阅读(63)  评论(0编辑  收藏  举报