Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[crud] Basic implementation #31416

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions packages/react-reconciler/src/ReactFiberCallUserSpace.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {CapturedValue} from './ReactCapturedValue';

import {isRendering, setIsRendering} from './ReactCurrentFiber';
import {captureCommitPhaseError} from './ReactFiberWorkLoop';
import {SimpleEffectKind} from './ReactFiberHooks';

// These indirections exists so we can exclude its stack frame in DEV (and anything below it).
// TODO: Consider marking the whole bundle instead of these boundaries.
Expand Down Expand Up @@ -177,11 +178,13 @@ export const callComponentWillUnmountInDEV: (

const callCreate = {
'react-stack-bottom-frame': function (effect: Effect): (() => void) | void {
const create = effect.create;
const inst = effect.inst;
const destroy = create();
inst.destroy = destroy;
return destroy;
if (effect.kind === SimpleEffectKind) {
const create = effect.create;
const inst = effect.inst;
const destroy = create();
inst.destroy = destroy;
return destroy;
}
},
};

Expand Down
91 changes: 88 additions & 3 deletions packages/react-reconciler/src/ReactFiberCommitEffects.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
enableProfilerNestedUpdatePhase,
enableSchedulingProfiler,
enableScopeAPI,
enableUseResourceEffectHook,
} from 'shared/ReactFeatureFlags';
import {
ClassComponent,
Expand Down Expand Up @@ -70,6 +71,7 @@ import {
} from './ReactFiberCallUserSpace';

import {runWithFiberInDEV} from './ReactCurrentFiber';
import {ResourceEffectKind, SimpleEffectKind} from './ReactFiberHooks';

function shouldProfile(current: Fiber): boolean {
return (
Expand Down Expand Up @@ -146,15 +148,45 @@ export function commitHookEffectListMount(

// Mount
let destroy;
if (
enableUseResourceEffectHook &&
effect.kind === ResourceEffectKind
) {
if (typeof effect.create === 'function') {
effect.resource = effect.create();
if (__DEV__) {
if (effect.resource == null) {
console.error(
'useResourceEffect must provide a callback which returns a resource. ' +
'If a managed resource is not needed here, use useEffect. Received %s',
effect.resource,
);
}
}
} else if (
typeof effect.update === 'function' &&
effect.resource != null
) {
// TODO(@poteto) what about multiple updates?
effect.update(effect.resource);
}
destroy = effect.destroy;
}
if (__DEV__) {
if ((flags & HookInsertion) !== NoHookEffect) {
setIsRunningInsertionEffect(true);
}
destroy = runWithFiberInDEV(finishedWork, callCreateInDEV, effect);
if (effect.kind === SimpleEffectKind) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto here for the feature flag behavior

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this one is still needed because i unconditionally change the shape of the Effect type, so we do still need this check. i could probably console.error or something if the flag is disabled and the effect kind isn't the simple one

destroy = runWithFiberInDEV(
finishedWork,
callCreateInDEV,
effect,
);
}
if ((flags & HookInsertion) !== NoHookEffect) {
setIsRunningInsertionEffect(false);
}
} else {
} else if (effect.kind === SimpleEffectKind) {
const create = effect.create;
const inst = effect.inst;
destroy = create();
Expand All @@ -176,6 +208,11 @@ export function commitHookEffectListMount(
hookName = 'useLayoutEffect';
} else if ((effect.tag & HookInsertion) !== NoFlags) {
hookName = 'useInsertionEffect';
} else if (
enableUseResourceEffectHook &&
effect.kind === ResourceEffectKind
) {
hookName = 'useResourceEffect';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto no failing test

} else {
hookName = 'useEffect';
}
Expand Down Expand Up @@ -244,9 +281,24 @@ export function commitHookEffectListUnmount(
if ((effect.tag & flags) === flags) {
// Unmount
const inst = effect.inst;
if (
enableUseResourceEffectHook &&
effect.kind === ResourceEffectKind &&
effect.resource != null &&
(effect.create != null ||
// TODO(@poteto) this feels gross
finishedWork.return == null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only works because in the tests the App component is the root component, so there's no return fiber to the parent. We need to find a better way to do this that works through multiple layers.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I.e. this test fails:

    it('unmounts on deletion after skipped effect', async () => {
      
      function Wrapper(props) {
        return <App {...props} />
      }
      function App({id, username}) {
        const opts = useMemo(() => {
          return {username};
        }, [username]);
        useResourceEffect(
          () => {
            const resource = new Resource(id, opts);
            Scheduler.log(`create(${resource.id}, ${resource.opts.username})`);
            return resource;
          },
          [id],
          resource => {
            resource.update(opts);
            Scheduler.log(`update(${resource.id}, ${resource.opts.username})`);
          },
          [opts],
          resource => {
            resource.destroy();
            Scheduler.log(`destroy(${resource.id}, ${resource.opts.username})`);
          },
        );
        return <Text text={'Id: ' + id} />;
      }

      await act(async () => {
        ReactNoop.render(<Wrapper id={0} username="Sathya" />, () =>
          Scheduler.log('Sync effect'),
        );
        await waitFor(['Id: 0', 'Sync effect']);
        expect(ReactNoop).toMatchRenderedOutput(<span prop="Id: 0" />);
      });

      assertLog(['create(0, Sathya)']);

      await act(async () => {
        ReactNoop.render(<Wrapper id={0} username="Lauren" />, () =>
          Scheduler.log('Sync effect'),
        );
        await waitFor(['Id: 0', 'Sync effect']);
        expect(ReactNoop).toMatchRenderedOutput(<span prop="Id: 0" />);
      });

      assertLog(['update(0, Lauren)']);

      ReactNoop.render(null);
      await waitForAll(['destroy(0, Lauren)']);
      expect(ReactNoop).toMatchRenderedOutput(null);
    });

) {
inst.destroy = effect.destroy;
}
const destroy = inst.destroy;
if (destroy !== undefined) {
inst.destroy = undefined;
let resource;
if (enableUseResourceEffectHook) {
resource = effect.resource;
effect.resource = null;
}
if (enableSchedulingProfiler) {
if ((flags & HookPassive) !== NoHookEffect) {
markComponentPassiveEffectUnmountStarted(finishedWork);
Expand All @@ -260,7 +312,16 @@ export function commitHookEffectListUnmount(
setIsRunningInsertionEffect(true);
}
}
safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);
if (enableUseResourceEffectHook) {
safelyCallDestroyWithResource(
finishedWork,
nearestMountedAncestor,
destroy,
resource,
);
} else {
safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);
}
if (__DEV__) {
if ((flags & HookInsertion) !== NoHookEffect) {
setIsRunningInsertionEffect(false);
Expand Down Expand Up @@ -895,6 +956,30 @@ function safelyCallDestroy(
}
}

function safelyCallDestroyWithResource(
current: Fiber,
nearestMountedAncestor: Fiber | null,
destroy: mixed => void,
resource: mixed,
) {
const destroy_ = resource == null ? destroy : destroy.bind(null, resource);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if you return null as the resource?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (__DEV__) {
runWithFiberInDEV(
current,
callDestroyInDEV,
current,
nearestMountedAncestor,
destroy_,
);
} else {
try {
destroy_();
} catch (error) {
captureCommitPhaseError(current, nearestMountedAncestor, error);
}
}
}

function commitProfiler(
finishedWork: Fiber,
current: Fiber | null,
Expand Down
Loading
Loading