Skip to content

useForwardedRef incorrectly updates the ref during the render phase #6551

@denis-sokolov

Description

@denis-sokolov

In #5462 the function useForwardedRef was changed so that now the ref is mutated during the render phase of React. This violates React’s expected invariant that render functions have no side-effects and conflicts with Concurrent React.

In some cases React warns about that in the console with: “Cannot update a component while rendering a different component. To locate the bad setState() ...”

In the latest master, notice how one updateRef is correctly in an effect, and the other is outside of an effect:

export const useForwardedRef = (ref) => {
const innerRef = useRef(null);
updateRef(ref, innerRef);
useLayoutEffect(() => updateRef(ref, innerRef));
useEffect(() => updateRef(ref, innerRef));
return innerRef;
};

PR change.

Expected Behavior

useForwardedRef should only mutate ref in the useEffect.

Actual Behavior

useForwardedRef mutates ref outside of an effect.

Metadata

Metadata

Assignees

Labels

bugissue that does not match design or documentation and requires code changes to address

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions