useError

React, Hooks, State, Effect

Creates an error dispatcher.

  • Use the useState() hook to create a state variable that holds the error.
  • Use the useEffect() hook to throw the error whenever it's truthy.
  • Use the useCallback() hook to update the state and return the cached function.
const useError = err => {
  const [error, setError] = React.useState(err);

  React.useEffect(() => {
    if (error) throw error;
  }, [error]);

  const dispatchError = React.useCallback(err => {
    setError(err);
  }, []);

  return dispatchError;
};
Rconst ErrorButton = () => {
  const dispatchError = useError();

  const clickHandler = () => {
    dispatchError(new Error('Error!'));
  };

  return <button onClick={clickHandler}>Throw error</button>;
};

ReactDOM.render(<ErrorButton />, document.getElementById('root'));

Recommended snippets

  • useWindowSize

    React, Hooks

    Tracks the dimensions of the browser window.

  • useSearchParam

    React, Hooks

    Tracks the browser's location search param.

  • usePersistedState

    React, Hooks

    Returns a stateful value, persisted in localStorage, and a function to update it.