Patterns
Consume feature in specific state
Sometimes you only want to consume a feature in a specific state, or states. This can be in an other feature or in a UI component. In these scenarios you should avoid using the hook and rather get the state of the feature as a prop from the outside.
interface Props {
someFeature: PickState<SomeFeature, 'SOME_STATE'>
}
const SomeUIComponent = ({ someFeature }: Props) => {
}Dynamic reducers
There are situations when the action handlers in the reducer needs access to state from other features or props. To avoid duplicating state you can make the reducer dynamic.
const featureReducer = (someOtherFeatureState: SomeOtherFeature[0]) => createReducer<SomeFeature>({
SOME_STATE: {
SOME_HANDLER: () => ({...})
}
})
interface Props {
initialState?: State
}
const Feature = ({ initialState }: Props) => {
const [someOtherFeatureState] = useSomeOtherFeature()
const feature = useReducer(
featureReducer(someOtherFeatureState),
initialState
)
}Lift action handlers
Sometimes you might have one or multiple action handlers across states. You can lift them up and compose them back into your transitions.
There are three parts to this patterns:
Only type what you need from an action, not the actions themselves
If you are consuming the current state, type it as any context (
State) and optionally restrict it with properties and values you want to be available on that stateAlways give
Transitionas the return type
You can define a single event handler:
Or multiple action handlers:
Match all the things
You can use match for more than rendering a specific UI. You can for example use it for styling:
You can even create your own UI metadata related to a state which can be consumed throughout your UI definition:
Subtype state for match
You might have functions that only deals with certain states.
match will infer the type of state and ensure type safety for the subtype.
Base state
Sometimes you have multiple states sharing the same base state. You can best express this by:
This expresses the simplest states first, then indents the states using the base state. This ensures that you see these states related to their base and with their indentation they have "additional meaning".
Nested states
You do not have to express the whole state at the root, you can split it up into nested states.
Now any use of match can be done on the sub states as well.
Last updated
Was this helpful?