0

I have a dropdown created with MUI Select, MenuItem, and FormControl.

The Select's onChange updates a state variable using useState's callback function:

const handleDropdownChange = (e) => setDropdownVariable(e.target.value)

The state variable is a useMemo dependency (one of several dependencies, simplified below):

const result = useMemo(() => expensiveCalculation(), [dropdownStateVariable])

Everything works as intended.

Problem: The dropdown does not close until expensiveCalculation has finished running. The delay is only 1-2 seconds at the most, but ideally I'd like to close the dropdown before/while the process is running.

expensiveCalculation is not fetching data, but processing it. The data-fetching is done before this point, within useEffect.

I've chosen useMemo for this because I anticipate the user may frequently switch between different values of dropdownStateVariable and would like to benefit from the performance optimization of using memoized results.

Based on some preliminary research and some of the answers I've seen, it seems like useMemo would be the correct choice for me. In that case, is there any way around the slight delay in closing the Select dropdown? On the other hand, using useEffect, I would be able to use a state loading variable to give immediate feedback that the request is being processed while asynchronously preparing the data - but I'd lose the benefit of memoization.

Any suggestions appreciated.

pez
  • 3,859
  • 12
  • 40
  • 72
  • JS runs on a single thread meaning if you click something in your list to close it BUT when you click it it also has to do that expensive calculations - then it will only close/rerender after its threat is empty (everything is done). You might be able to overcome this issue with async (promise) function so split it up. But my concern is - why you running and expensive calculations every time something happens to the dropdown and maybe the expensive calculations can be improved too to help this issue? – Lith Apr 17 '22 at 21:37
  • @Lith The dropdown is to change data being displayed. Async with useMemo is an issue – pez Apr 17 '22 at 21:42
  • hmh.. if you are using a dropdown that on press calculates something and changes the display of the content then why not remove the logic from onclick into something like useeffect? onClick you set the state to something new and close the dropdown (no logic there, simple and fast to execute) then on useEffect to listen to new state of whatever user clicked and then runs the expensive calculations and rerenders once done. In the mean time you might display a loader to indicate a user that something is happening (loading) in the display. IMO that would solve ur issue and be better UE – Lith Apr 17 '22 at 21:47

0 Answers0