Xeen
Xeen

Reputation: 7003

How to use useCallback on a custom hook?

I need this: const setError = useError(); as a dependency in useEffect, but since this function is used in other places as well (within the same component), whenever an error is thrown, my useEffect api re-fetches data.

Should I just disable the react-hooks/exhaustive-deps rule or is there some way out of this? If I try to wrap it in useCallback I get an error that hooks can only be used within the component itself.

edit

export const useError = (): ((error: any, title?: string) => void) => {
  const dispatch = useDispatch();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const setError = (error: any, title = 'Error'): void => {
    Sentry.captureException(error);
    const bodyText = error.message || error;
    const errorTitle = error.name || title;
    dispatch(
      setNotification({
        type: notificationTypes.prompt,
        title: errorTitle,
        bodyText,
        className: 'error',
        show: true,
      })
    );
  };

  return setError;
};

Upvotes: 9

Views: 14787

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281932

You can wrap the setError function with useCallback with an empty dependency in your custom hook before returning so that it is created only once

export const useError = (): ((error: any, title?: string) => void) => {
  const dispatch = useDispatch();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const setError = useCallback((error: any, title = 'Error'): void => {
    Sentry.captureException(error);
    const bodyText = error.message || error;
    const errorTitle = error.name || title;
    dispatch(
      setNotification({
        type: notificationTypes.prompt,
        title: errorTitle,
        bodyText,
        className: 'error',
        show: true,
      })
    );
  }, []);

  return setError;
};

With the above you might get a ESLint warning to add dispatch and Sentry as dependency to useCallback dependency array, you can add them to the dependency array since neither of disptach or Sentry would change

Upvotes: 7

Related Questions