I'm learning ReactJS, and performance optimisation. I just stumbled on a case I just cannot explain.
Below is the smallest code I could write showing the "issue" / strange behavior.
import { useState, useMemo, useCallback } from "react";
export function App(props) {
const [query, setQuery] = useState('');
const memoT = useMemo(() => (query + '_memo'), [query]);
function callback() {
console.log("callback : "+memoT)
}
const testCall = useCallback(() => callback(), []);
return (
<>
<input
type="text"
value={query}
onChange={event => setQuery(event.target.value)}
/>
<p>{memoT}</p>
<button onClick={testCall} >run testCall</button>
</>
);
}
What I would have expected : When called, callback read the memoT value from its object (maybe phishy here), and displays whatever is typed in the textfield + _memo.
What I have : When read inside callback, the value of memoT is always its initial value. But when read outside (actually when called in the App function), the memoT is correct, and is the one displayed.
What I understand/suspects : When the callback is created, it "remembers" the current state, and the memoT reference at that point ? But then ... how to I get my callback to read its object state ?
Since you don't define any deps for useCallback
(use the eslint-plugin-react-hooks
package to tell you when you're not doing that), it's capturing the first value of callback
, which in turn has captured the first value of memoT
.
The simplest approach: callback
's body should be within the useCallback
itself, and that callback should depend on the values it captures (just memoT
in this case).
const testCall = useCallback(() => {
console.log("callback:", memoT);
}, [memoT]);
testCall
still contains a function, like you'd expect.