Skip to content

Move responsibility for callback memoization to user? #115

@delucis

Description

@delucis

Currently useEffectListener takes callbacks & dependency arrays to pass to React’s useCallback memoization hook:

useEffectListener('rollDie', callback, dependencies)

While researching approaches for #111 and #112, I read this documentation for the React hooks 'exhaustive-deps' rule in more detail. If I understand correctly, there’s technically no completely correct way to useCallback to memoize a user-passed function. To be sure to catch all scenarios correctly, the hook in theory has to update when the function’s identity changes (so it should include the function itself in the dependencies of useCallback or useEffect). I’ve seen some heavily-used examples that don’t follow this rule either (like this useAsyncFn hook, which calls a user-passed function within useCallback without including it in the dependency array), so perhaps this is OK but the edge cases that are buggy, will be hard to debug for anyone who does run in to them.

The solution here would be to rely on users memoizing their listener functions themselves:

const callback = useCallback(() => {}, []);
useEffectListener('rollDie', callback);

This would make using useEffectListener slightly more verbose, but technically more correct 🤷.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions