Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add useLoadingSemaphore hook #13

Open
MichaelBelousov opened this issue Aug 3, 2021 · 0 comments
Open

add useLoadingSemaphore hook #13

MichaelBelousov opened this issue Aug 3, 2021 · 0 comments
Assignees

Comments

@MichaelBelousov
Copy link
Contributor

/**
 * a custom hook that makes it easier to manage
 * a loading state with multiple consumers that can
 * declare they are loading, such as a component waiting
 * on two separate network requests. Returns whether isLoading,
 * and a `startLoading` and `finishLoading` function to wrap around critical sections like so:
 * @example
 * useEffect(() => {
 *   startLoading();
 *   await networkFetch();
 *   finishLoading();
 * }, []);
 */
export function useLoadingSemaphore() {
  const [loadingSemaphore, setLoadingSemaphore] = React.useState(0);
  // use useRef to stabilize the references (ok since setLoadingSemaphore is guaranteed stable)
  const startLoading = React.useRef(() => setLoadingSemaphore((p) => p + 1))
    .current;
  const finishLoading = React.useRef(() => setLoadingSemaphore((p) => p - 1))
    .current;
  const isLoading = loadingSemaphore > 0;
  return {
    isLoading,
    startLoading,
    finishLoading,
  };
}

this hook is generic and useful, should consider it for adding

@MichaelBelousov MichaelBelousov self-assigned this Aug 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant