Skip to content

Possible bug in hooks sample code #1455

Description

@catamphetamine

In this section:
https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback

  const handleSubmit = useEventCallback(() => {
    alert(text);
  }, [text]);

Where useEventCallback is:

function useEventCallback(fn, dependencies) {
  const ref = useRef(() => {
    throw new Error('Cannot call an event handler while rendering.');
  });

  useLayoutEffect(() => {
    ref.current = fn;
  }, [fn, ...dependencies]);

  return useCallback(() => {
    const fn = ref.current;
    return fn();
  }, [ref]);
}

Which means useLayoutEffect() is re-run each time fn changes.
Since fn in the example is re-created on each render it means that useLayoutEffect() always re-runs.
But at the same time the fn function can't be not created on each render because it depends on text which is re-defined on each render.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions