Manage Effect Lifecycles with Effect Entities
masterWhen you call exec(effect), it returns an effect entity. You can store this entity in your state to gain control over the running effect later.
Stop an effect
Use exec.stop(entity) to explicitly stop an effect and run its cleanup function. All running effects are automatically cleaned up when the component unmounts.
Replace an effect
Use exec.replace(entity, effect) to stop an existing effect and immediately start a new one. This returns a new effect entity.
const timerReducer = (state, event, exec) => {
if (event.type === 'START') {
// Store the entity in state
return {
...state,
timer: exec(() => {
const id = setTimeout(() => { /* ... */ }, 1000);
return () => clearTimeout(id);
}),
};
} else if (event.type === 'STOP') {
// Stop using the stored entity
exec.stop(state.timer);
return state;
} else if (event.type === 'LAP') {
// Replace the existing effect with a new one
return {
...state,
timer: exec.replace(state.timer, () => doSomeDelay()),
};
}
return state;
};