Example:
const Clock = resource(({ on }) => {
const now = cell(Date.now());
const interval = setInterval(() => now.current = Date.now(), 1000);
on.cleanup(() => clearInterval(interval));
return now.current;
})
vs
const Clock = resource(({ on }) => {
const now = cell(Date.now());
const interval = setInterval(() => now.current = Date.now(), 1000);
on.cleanup(() => clearInterval(interval));
return () => now.current;
})
The reason:
- because the tracked data (
.current), would be immediately consumed in the resource() body, the whole thing would be torn down when the clock updates (create a new interval each second). By using a function, only the function invalidates, you retain state, and keep the interval.