Skip to content

Commit

Permalink
feat(UX): reduce flickering on loading
Browse files Browse the repository at this point in the history
  • Loading branch information
maxpatiiuk committed Jun 2, 2024
1 parent 6a38be5 commit 4cdeb7f
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/src/hooks/useAsyncState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import React from 'react';
import { crash } from '../components/Errors/assert';
import { LoadingContext } from '../components/Contexts/Contexts';

const loadingTimeout = 1000;

/**
* Like React.useState, but initial value is retrieved asynchronously
* While value is being retrieved, hook returns undefined, which can be
Expand Down Expand Up @@ -41,15 +43,18 @@ export function useAsyncState<T>(
* callback change, rather than give inconsistent state.
*/
React.useLayoutEffect(() => {
// If callback changes, state is reset while new state is fetching
setState(undefined);
/*
* If callback changes, state is reset to show the loading screen if
* new state takes more than 1s to load
*/
let timeout = setTimeout(() => setState(undefined), loadingTimeout);
const wrapped = loadingScreen
? loading
: (promise: Promise<unknown>): void => void promise.catch(crash);
wrapped(
Promise.resolve(callback()).then((newState) =>
destructorCalled ? undefined : setState(newState),
),
Promise.resolve(callback())
.then((newState) => (destructorCalled ? undefined : setState(newState)))
.finally(() => clearTimeout(timeout)),
);

let destructorCalled = false;
Expand Down

0 comments on commit 4cdeb7f

Please sign in to comment.