English | 简体中文
easy to learn, no sample code, no useless render, global sharing of react state.
inspired by hox.
yarn add @acte/mook
# Or
npm install --save @acte/mookBy calling createHooks with a custom Hook, it will return a pair of hooks, which is used for retrieving, updating and sharing data.
import{createHooks}from"mook";import{useState}from"react";functionuseCounter(initialValue){const[count,setCount]=useState(initialValue??0);constdecrement=()=>setCount(count-1);constincrement=()=>{setCount(count+1);}return{
count,
decrement,
increment
};}exportconst{wrapped : useCounterModel,standin : useRefCounterModelRef}=createHooks(useCounter);wrapped is the wrapped version hook of the input, it is used for retrieving data, updating data, and notifying its updates.
standin is a special hook function,which has the same return value of wrapped function。
The wrapped hook can be use just once, while the standin hook can be used multiple times.
import{useCounterModel,useRefCounterModel}from"./couter-model";functionApp(props){return(<divstyle={{textAlign:"center"}}><Component1/><Component2/><Component3/></div>)}functionComponent1(props){const{count, increment, decrement}=useCounterModel(10);return(<p>
Component 1: {count}<buttononClick={increment}>Increment</button><buttononClick={decrement}>decrement</button></p>);}functionComponent2(props){const{count, increment, decrement}=useRefCounterModel();return(<p>
Component 2: {count}<buttononClick={increment}>Increment</button><buttononClick={decrement}>decrement</button></p>);}functionComponent3(props){const{count, increment, decrement}=useRefCounterModel();return(<p>
Component 3: {count}<buttononClick={increment}>Increment</button><buttononClick={decrement}>decrement</button></p>);}declarefunctioncreateHooks<T,P>(hook: HookFunc<T,P>): WrappedHooks<T>Create a pair of hooks.
The parameter is a custom Hook, used for defining the logic of hook/model.
You can call it multiple times to create multiple hooks/models:
const{wrapped: useCounterModelA,standin:useRefCounterModelA}=createHooks(useCounter);const{wrapped: useCounterModelB,standin:useRefCounterModelB}=createHooks(useCounter);WrappedHooks
WrappedHooks is the return type of createHooks.
exportinterfaceWrappedHooks<T>{wrapped : HookFunc<T>;standin : StandInHook<T>;}wrapped
wrapped is the wrapped version hook of the input, it is used for retrieving data, updating data, and notifying its updates.
standin
standin is a special hook function,which return the refernece value of wrapped function return value。
typeDeps<T>=(model: T)=>unknown[];exporttypeStandInHook<T>=(depsFn?: Deps<T>)=>T;In order to control the data you want to subscribe precisely, you can pass an odditional depsFn function to standin.
constcounter=useRefCounterModel(model=>[model.count,model.x.y]);