Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Velover opened this issue Nov 21, 2024 · 0 comments
Labels
Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug

Comments

@Velover
Copy link

Velover commented Nov 21, 2024

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

@Velover Velover added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Nov 21, 2024
@Velover Velover changed the title Bug: Problem with StrictMode in debug (useEffect + useRef/Memo). useEffect ignores first value of useRef/Memo and uses second twice Bug: Problem with StrictMode in development (useEffect + useRef/Memo). useEffect ignores first value of useRef/Memo and uses second twice Nov 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug
Projects
None yet
Development

No branches or pull requests

1 participant