Getting “React limits the number of renders to prevent an infinite loop.” when passing state variable?
Why is it not always a good idea to use the state variable while updating an object using the state updater function?
When updating an object inside a `useState` using useEffect or useMemo, if you try to pass the state variable into the state updater function, you often encounter the issue of a missing dependency. If you attempt to include the state variable as a dependency, you might face the “Re-render too much” error in ReactJS.’
Code:
setOptionSet({
...optionSet,
voucher_ledger_name: {"name":"hello"},
});
Error:
How to fix it?
To fix is one can use the callback function inside state updater and use that to update the object inside the useState variable.
setOptionSet((previousValue) => ({
...previousValue,
voucher_ledger_name: {"name":"hello"},
}));
Now, by using the callback function in the state updater, you are not relying on the state value directly as a dependency in your React Hook. Hence, you will not encounter any of the associated warnings. Cheers!
Leave a Reply