Ask Question

ReactJS - How to implement custom hook with intial-state function

I want to impl. a custom hook, the initial state has to be computed and I do not want to compute the initial state on each re-render.
So I want to pass my custom hook an init-state function, exactly like you can do e.g. with useState(() => ({ ... })).
It would be nice if the solution would be in TypeScript.

Demo for my issue:

interface IUseMyCustomHook {
  foo: string;
  bar: string;
}
const useMyCustomHook = ({ foo, bar }: IUseMyCustomHook) => {

  return {
    ...
  };
}

const MyComponent = () => {
  const { ... } = useMyCustomHook(() => doSomeHeavyCalc());

  ....
}
ReactTypeScript

1127 views

AuthorΒ΄s AnkiCodes image

AnkiCodes

Last edited on

1 Answer available

Best answer

I think it depends if you want that computation be part of your state or if it should just be computed on the first render.

But depending on that you should be good with using useState or useMemo in your custom hook.

Example:

type HeavyCalcFn = () => number;

const useMyCustomHook = (heavyCalculation: HeavyCalcFn, { foo, bar }: IUseMyCustomHook) => {
  const calculatedStuff = useMemo(heavyCalculation, []);

  // do something with the calculated stuff
}

If it shouldn't be part of your state and you're using useMemo, make sure to provide an empty array, because else it will still be executed on every render.

πŸ‘
1
πŸŽ‰
1