DEV Community

Isaac de Oliveira Almeida
Isaac de Oliveira Almeida

Posted on

[Help] React OnClick on element

I just found out that when you give an element an OnClick attribute with any function, it doesn't store the reference to the function. Instead, it stores the version of the function at that current time. See:
` const showLength = () => {
console.log(a.length);
};

const [a, setA] = useState([

  • , ]);

    const add = (event) => {
    setA([...a,

  • ]); console.log(a); }; return (
    • add showLength
    • {a}
    ); }; `

    The output of this is a square, next to two buttons: add, and showLength

    Add increases the list and shows another square next to the first one, and showLength shows the current length of the list.

    My problem is that the first square also recieved the onClick function showLength, but it always prints "1". Does anyone know how to fix this?

  • Top comments (0)