Use the power of leslie in react with hooks.
function* StocksTable() {
const [stocks, setStocks] = useState([]);
const [date, setDate] = useState(Date.now());
// Periodically fetch most recent info every second, will automatically cancel
// if the component unmounts or the dependencies of the hook change
useLatest(function* () {
while (true) {
const data = yield fetchStocks(date);
setStocks(data);
yield delay(1000);
}
}, [setStocks, date]);
return (
<Table>{stocks}</Table>
);
}
In this example two things stand out:
while(true)
: This job runs periodically and only when the component is mounted, so it's safe to run infinite loops.[setStocks, date]
: This hook depends on thedate
variable, which means if it changes it will stop running the job and restart it with the new values.
See the leslie API for specifics on how these control flow functions work