Skip to content

Bug: Problem with StrictMode in development (useEffect + useRef/Memo). useEffect ignores first value of useRef/Memo and uses second twice #31607

Closed as not planned
@Velover

Description

@Velover

React version 18.3.1
StrictMode renders everything twice. and if the useRef value changes on the second render useEffect uses second version of useRef twice.
That can cause some memory leaks during development and unexpected behavior for useEffect

export function useTestHook() {
  const value = useRef(Math.random());
  console.log(value, "Given");
  useEffect(() => {
    console.log("Used in effect", value);
    return () => {
      console.log(value, "Cleared");
    };
  }, []);
}

output:

Object { current: 0.26757063192266095 } Given 

Object { current: 0.3384111276512609 } Given 
Used in effect Object { current: 0.3384111276512609 }

Object { current: 0.3384111276512609 } Cleared

Used in effect Object { current: 0.3384111276512609 }

the problem with that is the reference to the first object 0.2675... was lost
and the second object 0.3384... was cleared and used again

That breaks the program if the useRef/Memo should return the cleanup callback with the object
e.g

const [object, cleanup] = useRef(someFunc());
const [state, SetState] = useState(object.Get());
useEffect(() => {
  object.OnChanged(SetState);
  return cleanup;
}, []);

because it's going to do the cleanup for the newest object immediately after connection and loose the refference to object created during the first render

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution: StaleAutomatically closed due to inactivityStatus: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions