Skip to content

Instantly share code, notes, and snippets.

@frzi
Last active October 31, 2022 18:43
Show Gist options
  • Save frzi/c9de4fa77f59ff1fb465265e0b227761 to your computer and use it in GitHub Desktop.
Save frzi/c9de4fa77f59ff1fb465265e0b227761 to your computer and use it in GitHub Desktop.
useForceUpdate in React with hooks.
// Put me somewhere accessible.
const useForceUpdate = () => {
const [_, setState] = useState(0)
return () => setState(val => val + 1)
}
// Example.
const Component = () => {
const forceUpdate = useForceUpdate()
const onClick = () => forceUpdate()
return (
<div onClick={onClick}>
{Date.now()}
</div>
)
}
@frzi
Copy link
Author

frzi commented Apr 8, 2021

Yep! I actually ran into a similar issue as a matter of fact. Completely forgot I still had this gist somewhere rotting, collecting dust.
The fix is enitrely the same as yours:

export const useForceUpdate = () => {
	const [_, setState] = useState(false)
	return () => setState(val => !val)
}

Thanks for reminding me this broken piece of code was still publicly available. I'll update it 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment