useMutator
Allows you to do mutations on your state and record any changes that happen. No mutations should be done outside the passed in mutator function. This links up to the recorder and will trigger any components that reference the mutated data via useSnap
import { useMutator, useSnap } from 'diagon-react';
import React, { FC } from 'react';
import { useAppState } from './state';
type Props = { multiplier: number };
export const UseMutatorExample: FC<Props> = React.memo(({ multiplier }) => {
const state = useAppState();
const counter = useSnap(state, state => state.counter);
//A mutator without any arguments or dependencies.
const incrementByOne = useMutator(state, state => state.counter += 1);
//You can give arbitrary arguments to your mutators.
const add = useMutator(state, (state, amount: number) => state.counter += amount);
//If you directly reference a prop inside your mutator, add it to your dependency list.
// You could also have just passed it as an argument.
const multiply = useMutator(state, state => state.counter *= multiplier, [multiplier]);
return (
<div>
<div>value: {counter}</div>
<button onClick={incrementByOne}>Add One</button>
<button onClick={() => add(3)}>Add Three</button>
<button onClick={multiply}>Multiply</button>
</div>
);
});
Also, mutators can take any additional arguments that you like, and only the state will be closed upon.
Return Value
Returns a callback that can be executed anywhere that will both mutate your state and trigger your react component to re-render.
Parameters
state
The state you wish to mutate.
mutator
The function you wish to use to modify your state. This function
deps : any[]
(optional)
A standard React hooks dependency list will recreate your memoized mutator.