4

I have one select field and onselect event I have three setStates call to update my local states.

Observation: The number of setStates written causes that much re render. When I commented setState it reduced accordingly.

Ex:

<select name="cars" id="cars" onselect={(e) => handleSelect(e)}>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

const handleSelect = e => {
    setInvalid(false);
    setValue("some value");
    setError("some error");
};


My understanding was it will do batching and cause only one render. But got 3 re-renders. Any explanation to this?

Nikita Kumari
  • 309
  • 3
  • 7

1 Answers1

2

with react18 Automatic Batching gets applied by default ,if you have return n number of state updates inside a function react will only re-render the component once . If you want to stop this behavior you can use flushSync

import { flushSync } from "react-dom";
 const clickMe = () => {
    setName("abc");
    flushSync(() => {
      setCount(30);
      // react will create a re-render here
    });
    setAge(30);
    setPin(1111);
  };

so for the above example react will re-render your component twice when clicking on clickMe() function, but if you are on the older version < 18 the re-render will take place n number of times.

Aman Sadhwani
  • 2,902
  • 3
  • 16
  • 24
  • I have updated to react18. Now problem is with strict mode, in strict mode my app is not working as expected, it just shows initial loader where as when removed working properly. How to deal with this? – Nikita Kumari Jun 24 '22 at 12:56
  • @NikitaKumari not sure what are you referring here – Aman Sadhwani Jun 24 '22 at 13:20
  • const root = createRoot(document.getElementById("root")); root.render( ); My app is wrapped in StrictMode. But not working have gone through this link but didn't understood what to do https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-strict-mode – Nikita Kumari Jun 27 '22 at 07:01
  • Actually on load of there is one session fetch. Until that time loader is shown on UI and upon completion, one component have useSelector which extract session data and displays the data. But after upgrading to 18 and having StrictMode, useSelector is not giving updated value to the component. It continue showing loader. And without strictMode its working fine. I don't understand the problem. – Nikita Kumari Jun 27 '22 at 07:35