Skip to content

Commit b58b679

Browse files
committed
add improvement as per parisholley@8b4f71d
1 parent 813c0ae commit b58b679

File tree

1 file changed

+9
-19
lines changed

1 file changed

+9
-19
lines changed

src/index.ts

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -536,25 +536,15 @@ export function useState<S>(
536536
// https://github.com/avkonst/hookstate/issues/109
537537
// See technical notes on React behavior here:
538538
// https://github.com/apollographql/apollo-client/issues/5870#issuecomment-689098185
539-
const renders = React.useRef(0);
540-
React.useMemo(
541-
() => { return renders.current += 1 },
542-
// this will update the value when dependency changes
543-
// (which never happens by design) OR
544-
// when a third party does hot reload, eg: react-fast-refresh
545-
// (which we use to detect such a case below)
546-
[value.state]
547-
);
548-
React.useEffect(
549-
() => {
550-
const capture = renders.current;
551-
// The state is not destroyed intentionally
552-
// under hot reload case.
553-
return () => { capture === renders.current && value.state.destroy() }
554-
},
555-
// this will invoke the effect callback when a component is unmounted OR
556-
// when a third party does hot reload, eg: react-fast-refresh
557-
[]);
539+
const isEffectExecutedAfterRender = React.useRef(false);
540+
isEffectExecutedAfterRender.current = false; // not yet...
541+
542+
React.useEffect(() => {
543+
isEffectExecutedAfterRender.current = true; // ... and now, yes!
544+
// The state is not destroyed intentionally
545+
// under hot reload case.
546+
return () => { isEffectExecutedAfterRender.current && value.state.destroy() }
547+
});
558548
} else {
559549
React.useEffect(() => () => value.state.destroy(), []);
560550
}

0 commit comments

Comments
 (0)