From f02386302c429937cc2f38ad7342335bf3ee516b Mon Sep 17 00:00:00 2001 From: Jonathan Toung Date: Sun, 19 Jan 2025 14:39:22 -0800 Subject: [PATCH] fix(react-table): fix improper state update on unmounted component --- packages/react-table/src/index.tsx | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/packages/react-table/src/index.tsx b/packages/react-table/src/index.tsx index 132ea49083..bdd50bdae2 100755 --- a/packages/react-table/src/index.tsx +++ b/packages/react-table/src/index.tsx @@ -73,6 +73,17 @@ export function useReactTable( // By default, manage table state here using the table's initial state const [state, setState] = React.useState(() => tableRef.current.initialState) + // Keep track of whether the component on which this table is referenced is + // mounted to avoid setting state on an unmounted component + const isMountedRef = React.useRef(false) + React.useEffect(() => { + isMountedRef.current = true + + return () => { + isMountedRef.current = false + } + }, []) + // Compose the default state above with any user state. This will allow the user // to only control a subset of the state if desired. tableRef.current.setOptions(prev => ({ @@ -85,8 +96,10 @@ export function useReactTable( // Similarly, we'll maintain both our internal state and any user-provided // state. onStateChange: updater => { - setState(updater) - options.onStateChange?.(updater) + if (isMountedRef.current) { + setState(updater) + options.onStateChange?.(updater) + } }, }))