reactjs / reactjs/react.dev

"How to read an often-changing value from useCallback?" doesn't seem idiomatic

Open
#2,947 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

Custom hooks that take dependency arrays don't seem idiomatic (maybe I'm wrong). The biggest reason for that is that the React hooks lint doesn't check dependency arrays for anything except the primitive hooks.

In particular, I'd propose changing this:

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

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

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

to

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

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

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

// which should be used as
const callback = useEventCallback(useCallback((event) => {
  /* ... */
}, [/* dependencies */]));

This is slightly more abstract but also less likely to cause footguns. Alternatively, it might just be better to create a new function every render and store it in the ref (no use of dependencies at all).

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

  // Note this runs unconditionally
  useEffect(() => {
    ref.current = fn;
  });

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

// which should be used as
const callback = useEventCallback((event) => {
  /* ... */
});

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names useEventCallback and useCallback and presents two alternative dependency-array examples, but it does not identify repository files or tests. Start by locating the documentation or examples covering these hooks, then determine which guidance should be adopted and update the relevant material with an agreed recommendation.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.