0
import { useEffect, useRef } from "react";
export default function Test() {
    const testRef = useRef(0);

    useEffect(() => {
        console.log(testRef);
        testRef.current = 1;
        console.log(testRef);
    }, []);

    return <div></div>;
}

log from this code is :

{ current : 0 }
{ current : 1 }

Which is expected and understandable. However, when I give useRef an object like this:

import { useEffect, useRef } from "react";
export default function Test() {
    const testRef = useRef({
        num: 0,
    });

    useEffect(() => {
        console.log(testRef);
        testRef.current.num = 1;
        console.log(testRef);
    }, []);

    return <div></div>;
}

The console output is : { current : 1 } { current : 1 }

What is confusing me is how the first log prints 1 instead of 0. How does it log a state which is not yet updated ?

  • 1
    Do not trust a console.log. it can be misleading because the value can be different than what you expect with object. At least use JSON.stringify to have the value as string and not depending on the object reference. – Quentin Grisel May 01 '23 at 20:48
  • This can happen anywhere. https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch – Tushar Shahi May 01 '23 at 20:49
  • This is because objects are passed by reference even to `console.log` so by reference, it's overriding the object values. To avoid this you can use `JSON.stringify` instead to get the expected behavior. – Syed Uzair Bukhari May 01 '23 at 21:06

0 Answers0