react-state-mutations
State updates in React
may be asynchronous. In the case that you're using the previous state to calculate the next state, you could run into race conditions when React
attempts to batch your state changes together. The following example demonstrates the problem:
// Warning! This is the bad example.; { superprops; thisstate = count: 0 ; thishandleClick = thishandleClick; } { this; this; } { const count = thisstate; return <button type="button" onClick=thishandleClick> count </button> ; } ;
In the example above, since both setState
calls mutate the same key, those mutations can be merged together, and you may end up with it only incrementing each click by one since the last mutation will win. You can solve this by passing a function to setState
, as those are executed sequentially and will not run over each other. This is demonstrated in the example below:
; { superprops; thisstate = count: 0 ; thishandleClick = thishandleClick; } { this; this; } { const count = thisstate; return <button type="button" onClick=thishandleClick> count </button> ; } ;
The beauty of this approach is that you can begin to extract out the state mutation into a separate function that can then be reused. As in the following refactor:
; const incrementCount = count: count + 1 ; { superprops; thisstate = count: 0 ; thishandleClick = thishandleClick; } { this; this; } { const count = thisstate; return <button type="button" onClick=thishandleClick> count </button> ; } ;
This is the basis for this library. The increment
function is already defined for you, as well as various other utilities. This library additionally provides an easy interface for defining your own mutations that read from the previous state so that you never run into race conditions with your state mutations. Using react-state-mutations
, the final result would look like:
;; const incrementCount = ; { superprops; thisstate = count: 0 ; thishandleClick = thishandleClick; } { this; this; } { const count = thisstate; return <button type="button" onClick=thishandleClick> count </button> ; } ;
You can alternatively use this library in conjunction with the useState
feature in React. To get the equivalent as the above example working, you can use:
;; const Counter = { const count setCount = ; const onClick = { ; ; }; return <button type="button" onClick=onClick> count </button> ;}; ;
Or, you could use the built in useIncrement
hook, as in:
;; const Counter = { const count onIncrement = ; const onClick = { ; ; }; return <button type="button" onClick=onClick> count </button> ;}; ;
Getting started
Install this package through npm
(npm install react-state-mutations --save
) or yarn
(yarn add react-state-mutations
). You can then import and use the mutations from within your components.
In addition with the ability to create your own mutations, this package ships with some pre-built mutations, listed below.
There is also an equivalent version of each of these mutations that works on standalone values. This can be used in conjunction with React's useState
to manipulate state in a safe way. The equivalent version is named the same, with State
appended onto the end. i.e., the equivalent mutation for toggle
is toggleState
, which will effectively perform value => !value
. Finally, there are hooks built in that use those mutations, so in useToggle
for the above example.
append
Appends a value to a list, as in the example:
; const appendStudent = ; const prevState = students: name: "Harry" name: "Hermione" ;const nextState = prevState;// => { students: [{ name: "Harry" }, { name: "Hermione" }, { name: "Ron" }] }
With single values:
; const prevState = name: "Harry" name: "Hermione" ;const nextState = prevState;// => [{ name: "Harry" }, { name: "Hermione" }, { name: "Ron" }]
With hooks:
; const Students = { const students onAppend = ; // sometime later... ;};
With TypeScript, append
, appendState
, and useAppend
all accept an additional type argument for specifying which type the array will hold, as in:
append"students";
concat
Concatentate two lists, as in the example:
; const concatStudents = ; const prevState = students: name: "Harry" name: "Hermione" ;const nextState = prevState;// => { students: [{ name: "Harry" }, { name: "Hermione" }, { name: "Ron" }, { name: "Ginny" }] }
With single values:
; const prevState = name: "Harry" name: "Hermione" ;const nextState = prevState;// => [{ name: "Harry" }, { name: "Hermione" }, { name: "Ron" }, { name: "Ginny" }]
With hooks:
; const Students = { const students onConcat = ; // sometime later... ;};
With TypeScript, concat
, concatState
, and useConcat
all accept an additional type argument for specifying which type the array will hold, as in:
concat"students";
cycle
Cycles through a list of values, as in the example:
; const cycleHouse = ;const visitNextHogwartsHouse = ; const prevState = house: "Gryffindor" ;let nextState = ;// => { house: "Hufflepuff" } nextState = ;// => { house: "Ravenclaw" } nextState = ;// => { house: "Slytherin" } nextState = ;// => { house: "Gryffindor" }
With single values:
; const visitNextHogwartsHouse = ; const prevState = "Gryffindor";let nextState = ;// => "Hufflepuff" nextState = ;// => "Ravenclaw" nextState = ;// => "Slytherin" nextState = ;// => "Gryffindor"
With hooks:
; const HogwartsHouses = { const house onCycle = ; // sometime later... ;};
With TypeScript, cycle
, cycleState
, and useCycle
all accept an additional type argument for specifying which type the array will hold, as in:
; cycle"house";
decrement
Decrements a value, as in the example:
; const destroyHorcrux = ; const prevState = horcruxes: 7 ;const nextState = ;// => { count: 6 }
With single values:
; const prevState = 7;const nextState = ;// => 6
With hooks:
; const Horcruxes = { const count onDecrement = ; // sometime later... ;};
With TypeScript, decrement
, decrementState
, and useDecrement
enforce the number
type on arguments.
direct
Directly modifies a value. This is mainly valuable when used with combineMutations
, as otherwise you could just pass the value to setState
as normal. The code below uses combineMutations
with others as an example:
; const getCake = ;const becomeAWizard = ; const prevState = wizard: false cake: null ;const nextState = prevState;// => { wizard: true, cake: "chocolate" }
With single values:
; const getCake = ; const prevState = null;const nextState = ;// => "cake"
With TypeScript, direct
and directState
each accept an additional type argument for specifying which type of object will be assigned into the state.
filter
Filters a list, as in the example:
; const filterStudents = ;const findGryffindors = ; const prevState = students: name: "Harry" house: "Gryffindor" name: "Cedric" house: "Hufflepuff" name: "Pansy" house: "Slytherin" ; const nextState = ;// => { students: [{ name: "Harry", house: "Gryffindor" }] }
With single values:
; const findGryffindors = ; const prevState = name: "Harry" house: "Gryffindor" name: "Cedric" house: "Hufflepuff" name: "Pansy" house: "Slytherin" ; const nextState = ;// => [{ name: "Harry", house: "Gryffindor" }]
With hooks:
; const Students = { const students onFilter = ; // sometime later... ;};
With TypeScript, filter
, filterState
, and useFilter
all accept an additional type argument T
for specifying which type the array will hold. Additionally the filter function argument is enforced to be of the type ((value: T) => boolean)
, as in:
filterStatehouse === "Gryffindor";
increment
Increments a value, as in the example:
; const upgradeBroom = ; const prevState = Nimbus: 2000 ;const nextState = ;// => { Nimbus: 2001 }
With single values:
; const prevState = 2000;const nextState = ;// => 2001
With hooks:
; const Nimbus = { const version onIncrement = ; // sometime later... ;};
With TypeScript, increment
, incrementState
, and useDecrement
enforce the number
type on arguments.
map
Maps over a list, as in the example:
; const mapStudents = ;const graduateStudents = ; const prevState = students: name: "Harry" year: 2 name: "Ginny" year: 1 ; const nextState = ;// => { students: [{ name: "Harry", year: 3 }, { name: "Ginny", year: 2 }] }
With single values:
; const graduateStudents = ; const prevState = name: "Harry" year: 2 name: "Ginny" year: 1 ; const nextState = ;// => [{ name: "Harry", year: 3 }, { name: "Ginny", year: 2 }]
With hooks:
; const Students = { const students onMap = ; // sometime later... ;};
With TypeScript, map
, mapState
, and useMap
all accept an additional type argument T
for specifying which type the array will hold. Additionally the map function argument is enforced to be of the type ((value: T) => T)
, as in:
mapState;
mutate
Mutates a value, as in the example:
; const mutateLupin = ;const fullMoon = ; const prevState = Lupin: status: "Man" role: "Professor" ;const nextState = ;// => { Lupin: { status: "Wolf", role: "Professor" } }
With single values:
; const fullMoon = ; const prevState = status: "Man" role: "Professor" ;const nextState = ;// => { status: "Wolf", role: "Professor" }
With TypeScript, the object being used to mutate is enforced to be of type object
.
prepend
Prepends a value to a list, as in the example:
; const prependStudent = ; const prevState = students: name: "Harry" name: "Hermione" ;const nextState = prevState;// => { students: [{ name: "Ron" }, { name: "Harry" }, { name: "Hermione" }] }
With single values:
; const prevState = name: "Harry" name: "Hermione" ;const nextState = prevState;// => [{ name: "Ron" }, { name: "Harry" }, { name: "Hermione" }]
With hooks:
; const Students = { const students onPrepend = ; // sometime later... ;};
With TypeScript, prepend
, prependState
, and usePrepend
all accept an additional type argument for specifying which type the array will hold, as in:
prepend"students";
toggle
Toggles a boolean value, as in the example:
; const toggleWizard = ; const prevState = wizard: false ;const nextState = ;// => { wizard: true }
With single values:
; const prevState = false;const nextState = ;// => true
With hooks:
; const WizardStatus = { const isWizard onToggle = ; // sometime later, with Hagrid... ;};
With TypeScript, toggle
, toggleState
, and useToggle
enforce the boolean
type on arguments.
Advanced
There are a couple of advanced functions, for creating your own mutations, combining multiple mutations into one function, and creating your own hooks.
makeStandaloneMutation
Creates a mutation that modifies state. Takes as an argument a function that accepts a value and returns the modified value. As in the example:
; const encrypt = ; const encryptName = ; const prevState = name: "Harry" ;const nextState = ;// => { name: "yrraH" }
With Typescript, makeStandaloneMutation
accepts an additional type argument for specifying which type of value will be mutated. For example:
;
makeArgumentMutation
Creates a mutation that is a function that takes one argument, that itself returns a function that modifies state. Takes as a function that accepts a value that returns a return that accepts the state and returns the modifies value. As in the example:
; const add = ;const flyUp100Feet = 100; const prevState = currentHeight: 0 ;const nextState = ;// => { currentHeight: 100 }
With TypeScript, makeArgumentMutation
accepts two type arguments, for specifying which type of value will be mutated and for specifying the type of the argument to be passed in. For example:
;
combineMutations
Combines multiple mutations into a single mutation function. Takes any number of arguments and returns a singular mutation created out of the combination of them all. Can accept either mutations created through react-state-mutations
, or plain objects that are meant to be directly setting state.
If any "argument" mutations are passed in, combineMutations
will return a function that accepts any number of arguments, that themselves will be passed to the mutations in the order in which they appear in the list given to combineMutations
. As in the example:
; const addToTeam = ; const prevState = players: name: "Angelina" name: "Alicia" roster: 2; const nextState = prevState;// => {// players: [{ name: "Angelina" }, { name: "Alicia" }, { name: "Katie" }],// roster: 3// };
If all of the mutations that are passed in are "standalone" mutations, then
combineMutations
will return a function that simply accepts and modifies
the state. As in the example:
; const becomeAWizard = ; const prevState = wizard: false wizards: 0 ;const nextState = ;// => { wizard: true, wizards: 1 };
You can additionally pass plain objects into combineMutations
that are
intended to directly set state. In this case they will be folded into the
resultant function and treated as "standalone" mutations that do not accept
arguments. As in the example:
; const startFlying = ; const prevState = height: 0 flying: false ;const nextState = prevState;// => { height: 100, flying: true };
makeStandaloneHook
Creates a reusable hook based on a mutation that requires no further input. makeStandaloneHook
takes two arguments, the first behind the mutation and the second being the default initial value. For example, if you wanted to create a hook that would always multiply the previous value by 2, you could:
; const useDouble = ;
Then, you could use useDouble
in your components as any other hooks, as in:
const DoubleDouble = { const value onDouble = ; return <button type="button" onClick=onDouble> value </button> ;};
You can also pass a value to useDouble
in this example to start at a certain value.
With TypeScript, makeStandaloneHook
accepts an additional type argument for specifying which kind of value will be stored in state. For example,
;
makeArgumentHook
Creates a reusable hook based on a mutation that requires one argument. makeArgumentHook
takes two arguments (the same as makeStandaloneHook
), the first behind the mutation and the second being the default initial value. For example, if you wanted to create a hook that would count up values in succession, you could:
; const useAdder = ;
Then you could use useAdder
in your components as any other hooks, as in:
; const Sum = { const number setNumber = ; const onChange = ; const value onAdd = ; const onClick = ; return <> <input type="number" value=value onChange=onChange /> <button type="button" onClick=onClick> Add </button> </> ;};
With TypeScript, makeArgumentHook
accepts two additional type arguments for specifying which kind of value will be stored in state, and which kind of value will be accepted as an argument. For example,
;
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/CultureHQ/react-state-mutations.
License
The code is available as open source under the terms of the MIT License.