Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: UI Flickering When State Updated

I have a component that displays search data returned from the Spotify API. However, every time I update the state the UI flickers:

enter image description here Input:

            <DebounceInput
                debounceTimeout={300}
                onChange={handleChange}
            />

Hook:

const [searchResults, setSearchResults] = useState(null)

API call w/ Apollo:

 const searchSpotify = async (query) => {
    const result = await props.client.query({
        query: SearchTracks,
        variables: {
            query
        }
    })
    const tracks = result.data.searchedTracks
    setSearchResults(tracks)
}

Render:

        {searchResults &&
            <div className="search-results">
                    {searchResults.map((song) => (
                            <SongInfo key={song.id} {...song} />
                    ))}
            </div>
        }

I noticed it only happens on the first load. For example, if I were to type the query again it shows without flickering. Is there a better way to implement this so the UI doesn't flicker?

like image 333
Travis S. Avatar asked Mar 06 '19 21:03

Travis S.


Video Answer


1 Answers

Below are the frames that cause the flicker. What I think is happening is it takes some time for the images to load. While they are loading the items have reduced height. You should make sure SongInfo layout does not depend on whether the image has been loaded or not.

Images not loaded - items are collapsed:

enter image description here

Images were loaded:

enter image description here

like image 53
abadalyan Avatar answered Oct 24 '22 23:10

abadalyan