Ever got tired of repeating this pattern everywhere when you want to update just one key/value pair in your state?
Noticed the key/values you set in setState
aren't typechecked and wish you had type safety when doing this kind of thing?
setState(prevState => ({ ...prevState, [key]: value })
// `key` and `value` can be anything here, does not have to match the type of your State
It uses generics to infer the type of your state, restricting the key
and value
arguments to be allowed keys of your state and allowed values of your key!
Example:
// given this state:
const [x, setX] = React.useState({
foo: true,
bar: false,
hello: 'world'
});
updateStatePair(setX, 'foo', false);
// x.foo === false
updateStatePair(setX, 'fakekey', false);
// Argument of type '"fakekey"' is not assignable to parameter of type '"bar" | "foo" | "hello"'.ts(2345)
updateStatePair(setX, 'hello', false);
// Argument of type 'false' is not assignable to parameter of type 'string'.ts(2345)