apearce / use-init

It's like useMemo without your linter yelling at you

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

use-init

A simple hook to abstract away storing the result of an expensive operation in a ref. It takes a function as an argument which will be executed on the first render and the result will be stored in a ref. On subsequent renders, the current property of the ref will be returned without re-running the function.

Take this example from the React docs:

const playerRef = useRef(null);

if (playerRef.current === null) {
  playerRef.current = new VideoPlayer();
}

Instead you can just write:

const player = useInit(() => new VideoPlayer());

You then use the player by just calling player instead of player.current.

It does not take a dependency array and will never re-run the function even if something changes, so you could also think of it as:

const foo = useMemo(() => someExpensiveOperation(), []);

About

It's like useMemo without your linter yelling at you

License:MIT License


Languages

Language:TypeScript 100.0%