From dc715f6f513559d571cc09d9d0bd6f9a564dfb75 Mon Sep 17 00:00:00 2001 From: Leo Gonzalez Date: Thu, 20 Oct 2022 11:22:20 +0200 Subject: [PATCH] added cleanup to force update hook --- src/util.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/util.ts b/src/util.ts index 51846fe..be506f7 100644 --- a/src/util.ts +++ b/src/util.ts @@ -1,9 +1,24 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; export function useForceUpdate(): () => void { + const mounted = useRef(false); const [, updateState] = useState(0); + + function handleUpdate(): void { + if (mounted.current) { + updateState((state) => state + 1); + } + } + + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + return () => { - updateState((state) => state + 1); + handleUpdate(); }; }