Skip to content

Commit bb37b80

Browse files
committed
A possible fix to the memory leak issues with useEffect
Revert changes to unmount of fiber Fix Flow errors Fix prettier Add a __key field to create functions to check identity revert change
1 parent 051272f commit bb37b80

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

packages/react-reconciler/src/ReactFiberCommitWork.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,8 @@ function commitHookEffectList(
316316
}
317317
if ((effect.tag & mountTag) !== NoHookEffect) {
318318
// Mount
319-
const create = effect.create;
319+
const create = ((effect.create: any): () => mixed);
320+
effect.create = null;
320321
let destroy = create();
321322
if (typeof destroy !== 'function') {
322323
if (__DEV__) {

packages/react-reconciler/src/ReactFiberHooks.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export type Hook = {
6262

6363
type Effect = {
6464
tag: HookEffectTag,
65-
create: () => mixed,
65+
create: null | (() => mixed),
6666
destroy: (() => mixed) | null,
6767
inputs: Array<mixed>,
6868
next: Effect,
@@ -552,7 +552,20 @@ function useEffectImpl(fiberEffectTag, hookEffectTag, create, inputs): void {
552552
currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
553553
workInProgressHook = createWorkInProgressHook();
554554

555-
let nextInputs = inputs !== undefined && inputs !== null ? inputs : [create];
555+
let nextInputs;
556+
if (inputs !== undefined && inputs !== null) {
557+
nextInputs = inputs;
558+
} else {
559+
// Rather than storing the create function in the nextInputs, which might
560+
// cause memory issues due to shared context of the retained closure. We
561+
// can instead add field called "__key" and assign a symbol to the field.
562+
// We then store this symbol and use it as a key instead of the function.
563+
// Note: This will require the ES2015 Symbol polyfill.
564+
if (create.__key === undefined) {
565+
create.__key = Symbol();
566+
}
567+
nextInputs = [create.__key];
568+
}
556569
let destroy = null;
557570
if (currentHook !== null) {
558571
const prevEffect = currentHook.memoizedState;

0 commit comments

Comments
 (0)