A hook that acts similar to Reacts useState but computes in a seperate thread, returns a state, and cleans itself up on un-mount.
useState
import { seWorkerState } from 'use-react-hooks';
interface Controller { status: 'idle' | 'running' | 'error' | 'expired' | 'killed'; terminate: () => void;} const useWorkerState: <T extends (args: any) => any, R extends ReturnType<T>>( func: T, defaultState: R) => [ReturnType<T> | null, (args: Parameters<T>) => Promise<void>, Controller];
import React from 'react';import { useWorkerState } from 'use-react-workers'; // Heavy compute functionfunction fibonacci(n: number): number { return n <= 1 ? n : fib(n - 1) + fib(n - 2);} const MyCoolComponent = () => { const [calcNum, setCalcNum] = useState(0); const [fib, setFib] = useWorkerState(fibonacci, 0); // Will not block the main thread return ( <div> <h1>Fib Number: {fib}</h1> <input type="number" value={calcNum} onChange={({ target }) => setCalcNum(Number(target.value))} /> <button onClick={() => setFib(calcNum)}>Calc new state</button> </div> );};