React: Useprevious Hook Only Works If There Is 1 State In The Component. How To Make It Work If There Are Multiple States?
The docs suggests the folllowing to get previous state: function Counter() { const [count, setCount] = useState(0); const prevCount = usePrevious(count); return
Now
Solution 1:
I don't think this is the right approach.
How about a custom hook that sets up the state and returns a custom setter function that handles this logic for you.
functionuseStateWithPrevious(initial) {
const [value, setValue] = useState(initial)
const [prev, setPrev] = useState(initial)
functionsetValueAndPrev(newValue) {
if (newValue === value) return// optional, depends on the logic you want.setPrev(value)
setValue(newValue)
}
return [prev, value, setValueAndPrev]
}
Which you would use like:
function MyComponent() {
const [prevCount, count, setCount] = useStateWithPrevious(0)
}
Solution 2:
I was able to create an altered version of your hook that does seem to work:
functionusePrevious(value) {
const ref = useRef([undefined, undefined]);
if (ref.current[0] !== value) {
ref.current = [value, ref.current[0]];
}
return ref.current[1];
}
Playground here.
Post a Comment for "React: Useprevious Hook Only Works If There Is 1 State In The Component. How To Make It Work If There Are Multiple States?"