Closed qodesmith closed 1 year ago
const reducer = (prev, updater) => {
if (typeof updater === 'function') {
return { ...prev, updater(prev) }
} else {
return { ...prev, updater }
}
}
const [state, setState] = React.useReducer(reducer, initialState)
Well ain't that sexy
This refactor for the win:
import { useReducer } from 'react'
const reducer = (prevState, updater) => (
typeof updater === 'function'
? { ...prevState, ...updater(prevState) }
: { ...prevState, ...updater }
)
const useMergeState = (initialState = {}) => useReducer(reducer, initialState)
export default useMergeState
Sorry for getting to this so late. This is super useful and especially like how it's implemented with useReducer. Might be fun to talk a bit about how React actually builds useState with useReducer. I'm going to do a post on this soon :)
I wanted to make a PR but I don't know how Gatsby works so I figured I can leave the code here and let you decide if you'd like to publish it or not.
The idea is to mimc the functionality of the old
setState
as closely as possible:To me this is especially helpful in 3 scenarios:
useMergeState
Example usage