preact-scoped-model
provides a set of functions to create scoped model
instances with predefined business logic based on Preact Hooks and other utilities.
-
createNullaryModel
: creates a scoped model that doesn't need a props. The syntax is similar tocreateModel
but the options only accept thedisplayName
property. -
createStateModel
: creates a scoped model based onuseState
hook.
import { createStateModel } from 'preact-scoped-model';
const Counter = createStateModel(0);
// ...
<Counter.Provider>
{/* ... */}
</Counter.Provider>
// ...
const [state, setState] = useValue(Counter);
createReducerModel
: creates a scoped model based onuseReducer
hook.
import { createReducerModel } from 'preact-scoped-model';
const Counter = createReducerModel((state, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
});
// ...
<Counter.Provider>
{/* ... */}
</Counter.Provider>
// ...
const [state, dispatch] = useValue(Counter);
dispatch({ type: 'INCREMENT' });
createPropsSelectorModel
: creates a scoped model whose state is its props.
import { createPropsSelectorModel } from 'preact-scoped-model';
const UserDetails = createPropsSelectorModel();
// ...
<UserDetails.Provider name={name} email={email}>
{/* ... */}
</UserDetails.Provider>
// ...
const name = useSelector(UserDetails, (state) => state.name);