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

Memoize mutation callbacks #8526

Merged
merged 2 commits into from
Jan 11, 2023
Merged
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
3 changes: 2 additions & 1 deletion packages/ra-core/src/dataProvider/useCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {

import { useDataProvider } from './useDataProvider';
import { RaRecord, CreateParams } from '../types';
import { useEvent } from '../util';

/**
* Get a callback to call the dataProvider.create() method, the result and the loading state.
Expand Down Expand Up @@ -142,7 +143,7 @@ export const useCreate = <
);
};

return [create, mutation];
return [useEvent(create), mutation];
};

export interface UseCreateMutateParams<RecordType extends RaRecord = any> {
Expand Down
3 changes: 2 additions & 1 deletion packages/ra-core/src/dataProvider/useDelete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
MutationMode,
GetListResult as OriginalGetListResult,
} from '../types';
import { useEvent } from '../util';

/**
* Get a callback to call the dataProvider.delete() method, the result and the loading state.
Expand Down Expand Up @@ -387,7 +388,7 @@ export const useDelete = <
}
};

return [mutate, mutation];
return [useEvent(mutate), mutation];
};

type Snapshot = [key: QueryKey, value: any][];
Expand Down
3 changes: 2 additions & 1 deletion packages/ra-core/src/dataProvider/useDeleteMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
MutationMode,
GetListResult as OriginalGetListResult,
} from '../types';
import { useEvent } from '../util';

/**
* Get a callback to call the dataProvider.delete() method, the result and the loading state.
Expand Down Expand Up @@ -394,7 +395,7 @@ export const useDeleteMany = <
}
};

return [mutate, mutation];
return [useEvent(mutate), mutation];
};

type Snapshot = [key: QueryKey, value: any][];
Expand Down
3 changes: 2 additions & 1 deletion packages/ra-core/src/dataProvider/useUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
MutationMode,
GetListResult as OriginalGetListResult,
} from '../types';
import { useEvent } from '../util';

/**
* Get a callback to call the dataProvider.update() method, the result and the loading state.
Expand Down Expand Up @@ -418,7 +419,7 @@ export const useUpdate = <
}
};

return [update, mutation];
return [useEvent(update), mutation];
};

type Snapshot = [key: QueryKey, value: any][];
Expand Down
3 changes: 2 additions & 1 deletion packages/ra-core/src/dataProvider/useUpdateMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
MutationMode,
GetListResult as OriginalGetListResult,
} from '../types';
import { useEvent } from '../util';
import { Identifier } from '..';

/**
Expand Down Expand Up @@ -420,7 +421,7 @@ export const useUpdateMany = <
}
};

return [updateMany, mutation];
return [useEvent(updateMany), mutation];
};

type Snapshot = [key: QueryKey, value: any][];
Expand Down
37 changes: 16 additions & 21 deletions packages/ra-core/src/store/useStore.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react';
import isEqual from 'lodash/isEqual';

import { useEventCallback } from '../util';
import { useEvent } from '../util';
import { useStoreContext } from './useStoreContext';

/**
Expand Down Expand Up @@ -64,26 +64,21 @@ export const useStore = <T = any>(
return () => unsubscribe();
}, [key, subscribe, defaultValue, getItem, value]);

const set = useEventCallback(
(valueParam: T, runtimeDefaultValue: T) => {
const newValue =
typeof valueParam === 'function'
? valueParam(value)
: valueParam;
// we only set the value in the Store;
// the value in the local state will be updated
// by the useEffect during the next render
setItem(
key,
typeof newValue === 'undefined'
? typeof runtimeDefaultValue === 'undefined'
? defaultValue
: runtimeDefaultValue
: newValue
);
},
[key, setItem, defaultValue, value]
);
const set = useEvent((valueParam: T, runtimeDefaultValue: T) => {
const newValue =
typeof valueParam === 'function' ? valueParam(value) : valueParam;
// we only set the value in the Store;
// the value in the local state will be updated
// by the useEffect during the next render
setItem(
key,
typeof newValue === 'undefined'
? typeof runtimeDefaultValue === 'undefined'
? defaultValue
: runtimeDefaultValue
: newValue
);
});
return [value, set];
};

Expand Down
2 changes: 1 addition & 1 deletion packages/ra-core/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import warning from './warning';
import useWhyDidYouUpdate from './useWhyDidYouUpdate';
import { getMutationMode } from './getMutationMode';
export * from './mergeRefs';
export * from './useEventCallback';
export * from './useEvent';

export {
escapePath,
Expand Down
41 changes: 41 additions & 0 deletions packages/ra-core/src/util/useEvent.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { fireEvent, render, screen } from '@testing-library/react';
import * as React from 'react';
import { useEvent } from './useEvent';

describe('useEvent', () => {
const Parent = () => {
const [value, setValue] = React.useState(0);
const handler = useEvent(() => {
return 1;
});

return (
<>
<span>Parent {value}</span>;
<button onClick={() => setValue(val => val + 1)}>Click</button>
<Child handler={handler} />
</>
);
};

const Child = React.memo(({ handler }: { handler: () => number }) => {
const [value, setValue] = React.useState(0);
React.useEffect(() => {
setValue(val => val + 1);
}, [handler]);

return <span>Child {value}</span>;
});

it('should be referentially stable', async () => {
render(<Parent />);
expect(screen.getByText('Parent 0')).not.toBeNull();
expect(screen.getByText('Child 1')).not.toBeNull();
fireEvent.click(screen.getByText('Click'));
expect(screen.getByText('Parent 1')).not.toBeNull();
expect(screen.getByText('Child 1')).not.toBeNull();
fireEvent.click(screen.getByText('Click'));
expect(screen.getByText('Parent 2')).not.toBeNull();
expect(screen.getByText('Child 1')).not.toBeNull();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,16 @@ const useLayoutEffect =
* @see https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
* @see https://github.com/facebook/react/issues/14099#issuecomment-440013892
*/
export const useEventCallback = <Args extends unknown[], Return>(
fn: (...args: Args) => Return,
dependencies: any[]
export const useEvent = <Args extends unknown[], Return>(
fn: (...args: Args) => Return
): ((...args: Args) => Return) => {
const ref = React.useRef<(...args: Args) => Return>(() => {
throw new Error('Cannot call an event handler while rendering.');
});

useLayoutEffect(() => {
ref.current = fn;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fn, ...dependencies]);
});

return useCallback((...args: Args) => ref.current(...args), []);
};