function SchrödingersDiff()
{
const [count, setCount] = useState(0);
// simulate a changing state
useEffect(() =>
{
const int = window.setInterval(() => setCount(s => s + 1), 1000);
return () => window.clearInterval(int);
}, []);
const last = useRef(0);
const diff = useMemo(() =>
{
const lastValue = last.current;
last.current = count;
const diff = count - lastValue;
// console.log(diff);
return diff;
}, [count]);
// console.log(diff);
return diff;
}
Why does this component always render "0" when running under <React.StrictMode>? It works fine (i.e. renders "1") without strict mode.
I know strict mode renders things twice, which would explain it, but I would expect useMemo to catch that - and it does: the log in the memo function prints the correct "1" every second. Even the one outside does.
Is there a better way to calculate that diff?
This is my actual useState/useEffect/setInterval, already adapted to keep the last:
export function useChannel(channelName, initialData, currentOnly)
{
const socket = useSc(s => s.socket); // gets a SocketCluster socket
const [data, setData] = useState(currentOnly ? initialData : {current: initialData});
useEffect(() =>
{
if (!socket) return;
const channel = socket.subscribe(channelName);
(async () =>
{
for await (const data of channel) setData(currentOnly ? data : s => ({current: data, last: s.current}));
})();
return () => channel.unsubscribe();
}, [socket, channelName]);
return data;
}