create-hook-context
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

create-hook-context

A more powerful version of React.createContext. Accepts a hook that takes in props for a provider, and then returned value of the hook, is the value provided to the context's consumers.

Signature:

 
import createContext from 'create-hook-context';
 
const [ThemeProvider, useTheme, withThemeProvider, ThemeContext] = createContext(
  ({ theme }) => theme, // hook that provides values for context given input
  {}, // defaultValue for context
  "Theme" // displayName for Context
)
 
const Consumer = () => {
  const val = useTheme();
  return <pre>{JSON.stringify(val)}</pre>;
};
 
const App = () => {
  return (
    <ThemeProvider theme={{ a: 1 }}>
      <Consumer />
    </ThemeProvider>
  );
};
 
/* or can use withThemeProvider to wrap components */
 
const App = withThemeProvider({ theme: { a: 1 } }, () => {
  const val = useTheme();
  return <pre>{JSON.stringify(val)}</pre>;
});
 
 

Readme

Keywords

none

Package Sidebar

Install

npm i create-hook-context

Weekly Downloads

7

Version

1.0.0

License

MIT

Unpacked Size

19.2 kB

Total Files

18

Last publish

Collaborators

  • nksaraf