Search code examples
javascriptreactjsreact-hooksuse-effect

Two state variables change but only want to re-render once


https://codesandbox.io/s/ancient-rain-19d4rb?file=/src/App.js

I created a sandbox above to demonstrate the problem that I am having. Please play with it and look at the code to see what it's doing.

enter image description here The left side has selections for the 'gamemode' and for each gamemode there exists options 'options' on the right side.

The API call requires both of these values to be inputted.

Whenever I change the option on the right, it should do an API call in Game.js If I change the gamemode on the left, it should also automatically change the option on the right to be the 0th index. With my current logic, it does two API calls whenever I change the gamemode since it's also changing the option. (Look at the console when changing modes)

How can I change the design or how can I adjust things to get the result I'm looking for?

Let me know if further clarification is needed.


Solution

  • The problem is that you have two pieces of state that depend on each other, being observed independently by another object causing unnecessary useEffect calls. One way to solve this is to create another state object that combines both gamemode and option and have Game.js observe this object only. This way, you can add your own custom logic to dictate exactly when the API should be called.

    Here's a sandbox with the solution implemented: https://codesandbox.io/s/dazzling-galileo-sj29fh?file=/src/App.js

    The first useEffect depends on option and immediately updates the game object when changed. The second useEffect depends on gamemode and first checks if the option needs to be updated to the 0th index, otherwise it updates the game directly.