I allow users to search for other users within my component using a query state variable to track this. Whenever this query changes, after a timeout, the query is performed and the new users are mapped on screen. Here is the code for this:
const [query, setQuery] = useState("")
const [users, setUsers] = useState([])
const [isLoading, setIsLoading] = useState(false)
const [noResultsFound, setNoResultsFound] = useState(false)
useEffect(() => {
if (query === "" || !query) return
let timer = setTimeout(async () => {
setIsLoading(true)
const res = await axiosPrivate.get(`${BASE_URL}/api/users/get_users/${query}`, { headers: { "x-auth-token": token } })
if (res?.data?.length === 0) {
setUsers([])
setNoResultsFound(true)
} else {
setUsers(res.data)
setNoResultsFound(false)
console.log(users)
}
setIsLoading(false)
}, 500)
return () => {
clearTimeout(timer)
}
}, [query])
Then I map the users array on the screen if they are available, otherwise I display a loading indicator. If no results were found for the query, then some text indicating this is displayed instead.
{isLoading && (
<Spinner
noDelay={true}
withStyles={false}
/>
)}
{!isLoading && noResultsFound === false && users.length > 0 && (
<>
{users.map((user) => (
<p key={uuidv4()}{ user.username}</p>
))}
</>
)}
{!isLoading && noResultsFound === true && users.length === 0 && <p>No users</p>}
The problem I have is that if the query changes, and the exact same results are returned from the API, a flicker occurs for each of the users list items. I have ensured all my keys for the mapped items are unique. How can I ensure that if the exact same results are returned from the API, then don’t re-render the list items to avoid the flicker on screen. If this is not a solution, is there any potential methods I could use in order to avoid this flickering? Thanks.