Last active
May 21, 2022 04:44
-
-
Save rafaelgandi/b672ecf45dfdea47103d7f311669212a to your computer and use it in GitHub Desktop.
useSpecialEffect() hook
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 [someValue1, setSomeValue1] = useState(null); | |
const [someValue2, setSomeValue2] = useState(false); | |
const anotherValueThatCanChange = "some other value"; | |
const [someValue0, setSomeValue0] = useState(true); // Some state that we don't necessarily want to track changes | |
// This hook will run on every render... similar to useEffect(()=>{}) | |
useSpecialEffect((prev) => { | |
if (prev.hasChanged({someValue1}, {anotherValueThatCanChange})) { | |
// Do stuff if someValue1 or anotherValueThatCanChange is updated | |
} | |
if (prev.hasChanged({someValue2})) { | |
// Do stuff if someValue2 got updated ... | |
if (someValue0) { // Access an untracked state and always be confident that it is the fresh value. | |
// Do stuff with someValue0's value. This value will always be the fresh value even though the hook | |
// is not tracking its changes. | |
} | |
} | |
}, {someValue1, someValue2, anotherValueThatCanChange}); // Tell the hook to track the changes of these variables | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment