Mimic class properties with useEventCallback#1566
Conversation
|
function useEventCallback<T extends (...args: any[]) => any>(
fn: T
): T {
const ref: any = React.useRef();
// we copy a ref to the callback scoped to the current state/props on each render
React.useLayoutEffect(() => {
ref.current = fn;
});
return React.useCallback((...args) => ref.current.apply(void 0, args), []) as T;
}as per facebook/react#14099 (comment) To me this would make it more clear that That is to say, even the current version does essentially this, but Edit Another thing that falls off from this change is, now whenever |
In v1, all helper methods we class properties. This meant that they were bound to the instance of the class. However, with hooks, there is no concept of
thisand each helper method is wrapped inuseCallback. However, certain behaviors (e.g. auto-saving) are not possible because of circularuseCallbackdependencies. For example,submitFormdepends onvalues, so if you changevalues, thensubmitFormwill be different. This prevents you from debouncingsubmitFormin response tovaluesbecause you get a brand new function on each change. Sadness.The suggested solution in the React docs is to use this hook:
This PR adds this hook internally and utilizes it where necessary (on any callback that relies on
state). It also adds a newDebouncedAutoSaveexample to the examples directory.