Created
May 11, 2020 13:48
-
-
Save finom/f03e6faa278c1e40e2c79ccea0bb8468 to your computer and use it in GitHub Desktop.
[finom/use-force-update] Allows to make force re-render of react components
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 [forceIndex, forceUpdate] = useForceUpdate(); | |
// call forceUpdate() when component needs to be updated | |
// use forceIndex as key to force re-render child components | |
Important! This function is most likely an antipattern! But sometimes I can be super useful: | |
it can re-render react native screens when something gone wrong and user is prompted by a "Try again" button. | |
*/ | |
import { useState, useCallback } from 'react'; | |
export default function useForceUpdate() { | |
const [value, setValue] = useState(0); | |
return [value, useCallback(() => setValue((val) => val + 1), [value])]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment