Created
June 19, 2020 17:27
-
-
Save danedavid/65d0720a0141282e9f60c8e0fdb4f2ea to your computer and use it in GitHub Desktop.
Custom React hook for fetching previous props & state values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Usage */ | |
const Counter = ({ upperCount }) => { | |
const [count, setCount] = useState(1); | |
usePrevValues( | |
{ | |
count, | |
upperCount | |
}, | |
prevValues => { | |
if (prevValues.count + 1 === count) { | |
console.log("state change"); | |
} | |
if (prevValues.upperCount + 1 === upperCount) { | |
console.log("prop change"); | |
} | |
} | |
); | |
return ( | |
<> | |
<div>upper count: {upperCount}</div> | |
<div>inner count: {count}</div> | |
<button onClick={() => setCount(count + 1)}>Increment</button> | |
</> | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const usePrevValues = (value, callback) => { | |
const prevValues = useRef(value); | |
useEffect(() => { | |
callback(prevValues.current); | |
return () => (prevValues.current = value); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment