Share
HookwithContext
English | 简体中文
import React, { useState } from 'react';
import createConuse from 'conuse';
// 1️⃣ Create a custom hook
const useCounter = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(prevCount => prevCount + 1);
return { count, increment };
};
// 2️⃣ Wrap your hook with the createConuse factory
const { ConuseProvider, useConuseContext } = createConuse({ counter: useCounter });
function Button() {
// 3️⃣ Use context instead of custom hook
const { increment } = useConuseContext('counter');
return <button onClick={increment}>+</button>;
}
function Count() {
// 4️⃣ Use context in other components
const { count } = useConuseContext('counter');
return <span>{count}</span>;
}
function App() {
// 5️⃣ Wrap your components with Provider
return (
<ConuseProvider>
<Count />
<Button />
</ConuseProvider>
);
}npm:
npm i conuseYarn:
yarn add conuseConuse library exports a single factory method called createConuse which return conuse type, as follow:
Conuse {
ConuseProvider: React.FC<any>;
useConuseContext: (name?: string) => any;
getContext: (name?: string) => any;
}
Type: { [name: string]: hook }
It receives custom hook map, using it to compose multiple hook. You can get one hook by passing name to useConuseContext parameter.
const { useConuseContext } = createConuse({ counter: useCounter });
const Component = () => {
const { count } = useConuseContext('counter');
return count;
};Type: Conuse
Using it to compose multiple conuse.
const toggleConuse = createConuse({ toggle: useToggle });
const { useConuseContext } = createConuse({ counter: useCounter }, { toggle: toggleConuse });
const Component = () => {
const { count } = useConuseContext('counter');
const { toggle } = useConuseContext('toggle');
return `${count}${toggle}`;
};Type: React.FC<any>
Just like Context.Provider, to put the ConuseProvider at the top of your App.
<ConuseProvider>
<App />
</ConuseProvider>Type: (name?: string) => any
The children of ConuseProvider can get certain hook by useConuseContext.
const [value, setValue] = useConuseContext(<name>)The name parameter must be one of the keys of useMap, and you can get the returned of relevant hook which will be executed.
If you want to get all hooks, not passing name to useConuseContext. But the return of useConuseContext() is all hooks, not the
returned of all hooks, you need to execute hook function to get state and setState.
Type: (name?: string) => any
The difference between getContext and useConuseContext is getContext can be used everywhere, not only in Function Component.
Thanks to constate and unstated-next incredible work, and learned a lot from @kentcdodds' Application State Management with React.