4 ms·
I've had to write my own `useCallbackOne()` hook that is guaranteed to not be recomputed if it's dependencies don't change. export function useMemoOne<T>(v
by davidatbu 4y ago
I've had to write my own `useCallbackOne()` hook that is guaranteed to not be recomputed if it's dependencies don't change.
export function useMemoOne<T>(valueProducer: () => T, deps: unknown[]) {
const [initialValue] = useState(valueProducer);
const memoizedValue = useRef(initialValue);
const memoizedDeps = useRef(deps);
if (
deps.length != memoizedDeps.current!.length ||
_.zip(deps, memoizedDeps.current!).some(
([dep, memoizedDep]) => dep != memoizedDep
)
) {
memoizedValue.current = valueProducer();
memoizedDeps.current = deps;
}
return memoizedValue.current;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useCallbackOne<T extends (...args: any[]) => unknown>(
fn: T,
deps: unknown[]
) {
return useMemoOne(() => fn, deps);
}
FWIW, for this and other reasons, I've recently been looking into "actually reactive" frameworks (like Solid/Svelte), and I think I vastly prefer their paradigm to react's.
Specifically, I used sycamore-rs to build a Rust/WASM UI, and it's great (once you get the hang of dealing with lifetimes in sycamore).