Skip to content

Instantly share code, notes, and snippets.

@finom
Created May 11, 2020 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finom/f03e6faa278c1e40e2c79ccea0bb8468 to your computer and use it in GitHub Desktop.
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
/*
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