⊗jsrxPmATADR 49 of 57 menu

Eliminating duplicate requests in Redux

This lesson will be useful to us if, when launching the application, we duplicate the sending of a data request, and then pairs of products with the same id arrive, and, as a result, scary red warnings appear in the browser console.

The reason for this is the peculiarity of mounting components in React 18 and higher in development mode (dev), when using React.StrictMode (they say that in production mode everything is ok with this). First, the component is connected, then disconnected and connected again. That's why the request is sent twice.

Perhaps, when you study this material, this double mounting in React will already be changed in some way. We will not go into the details, but for now we will just use React hook useRef, which will help us to bypass this misunderstanding.

Let's open our product app, and in it the file ProductsList.jsx. Let's import the hook useRef into it:

import { useEffect, useRef } from 'react'

Now let's change the following code block with useEffect a little:

useEffect(() => { if (productStatus === 'idle') { dispatch(fetchProducts()) } }, [productStatus, dispatch])

First, we introduce a new variable dataFetch for useRef. Initially, we set its current property to false. If the application has already been launched and, accordingly, the request has been sent, then the current property will already be true, which means we will simply exit the function and the data request will not be repeated. So, the above piece of code will now look like this:

const dataFetch = useRef(false) useEffect(() => { if (dataFetch.current) return dataFetch.current = true if (productStatus === 'idle') { dispatch(fetchProducts()) } }, [productStatus, dispatch])

Now let's run our application again and be relieved to see the disappearance of red warnings in the console, and see a list of products without duplicates, now there are 8, as we planned on the server. Now in Redux DevTools, the actions generated by the request are no longer repeated.

Open your app with students, and in it the file StudentsList.jsx. Fix the double request issue according to the lesson materials, if you have one.

enru