Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reconsider how you're using useEffect - refactor to use fewer of them #25

Open
snphillips opened this issue Aug 12, 2023 · 0 comments
Open

Comments

@snphillips
Copy link
Owner

Many times in the app I am using useEffect as a 'subscription'. This ticket involves reconsidering all times I am using it, and finding other solutions.

  1. when round changes
  2. when attempt changes
  3. when lostRounds changes
  4. when gameState changes

"useEffect is best used for side-effects, but here you're using it as a sort of "subscription" concept, like: "do X when Y changes". That does sort of work functionally, due to the mechanics of the deps array, but it's not the intended purpose."
https://stackoverflow.com/questions/58866796/understanding-the-react-hooks-exhaustive-deps-lint-rule]

Further reading:
https://react.dev/learn/you-might-not-need-an-effect

How to remove unnecessary Effects
There are two common cases in which you don’t need Effects:

You don’t need Effects to transform data for rendering. For example, let’s say you want to filter a list before displaying it. You might feel tempted to write an Effect that updates a state variable when the list changes. However, this is inefficient. When you update the state, React will first call your component functions to calculate what should be on the screen. Then React will “commit” these changes to the DOM, updating the screen. Then React will run your Effects. If your Effect also immediately updates the state, this restarts the whole process from scratch! To avoid the unnecessary render passes, transform all the data at the top level of your components. That code will automatically re-run whenever your props or state change.
You don’t need Effects to handle user events. For example, let’s say you want to send an /api/buy POST request and show a notification when the user buys a product. In the Buy button click event handler, you know exactly what happened. By the time an Effect runs, you don’t know what the user did (for example, which button was clicked). This is why you’ll usually handle user events in the corresponding event handlers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant