Skip to content

Instantly share code, notes, and snippets.

@jakobvase
Last active May 1, 2023 13:12
Show Gist options
  • Save jakobvase/2ecbe605203db43bdb9f882f517f9a69 to your computer and use it in GitHub Desktop.
Save jakobvase/2ecbe605203db43bdb9f882f517f9a69 to your computer and use it in GitHub Desktop.
This is a workaround to the fact that errors thrown in `useEffect` and similar cause the whole react tree to unmount. It takes the error and throws it inside the render tree instead.
/**
* This is a workaround to the fact that errors thrown in `useEffect` and similar cause the whole
* react tree to unmount. It takes the error and throws it inside the render tree instead.
*
* Taken from https://www.developerway.com/posts/how-to-handle-errors-in-react and
* https://github.com/facebook/react/issues/14981#issuecomment-468460187.
*
* Usage:
* ```
* const Component = () => {
* const throwUnhandledError = useThrowUnhandledError();
*
* useEffect(() => {
* try {
* // something dangerous
* } catch(e) {
* throwUnhandledError(e);
* }
* })
* }
* ```
*/
export const useThrowUnhandledError = () => {
const setState = useState()[1];
return useCallback(
(error: Error) =>
setState(() => {
throw error;
}),
[setState]
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment