Please don't. useEffect() is for pluging 3rd party DOM components into react. Not for doing anything else. Definitely not for any state manipulation or dependencies.
Please don't. useEffect() is for pluging 3rd party DOM components into react. Not for doing anything else. Definitely not for any state manipulation or dependencies.
- useEffect is a React Hook that lets you synchronize a component with an external system.
- Connecting to an external system
- Wrapping Effects in custom Hooks
- Controlling a non-React widget
- Fetching data with Effects
- Specifying reactive dependencies
- Updating state based on previous state from an Effect
- Removing unnecessary object dependencies
- Removing unnecessary function dependencies
- Reading the latest props and state from an Effect
- Displaying different content on the server and the client
https://react.dev/reference/react/useEffect#specifying-react...
What you should have gotten from this list of every possible use (and misuse) of useEffect is that it's for interaction with external things. And if you are doing a lot of interafacing with external stuff you should use a dedicated service for it, not pollute your code with ad-hoc bits of interaction, each wrapped in their own bespoke useEffect().
And the linked section talks about specifying dependencies of the code block inside useEffect()
You don't define dependencies WITH useEffect. You define dependencies OF useEffect. And you don't have much choice in the matter. Any local variable (also parameter) of render function needs to be a dependency of useEffect code. As this section states.
Here are some common misuses: https://react.dev/learn/you-might-not-need-an-effect
React is UI library. Just because it can do a lot doesn't mean it should do everything. Especially in larger apps.
Or you could write your router in the form of a service that lives directly in the history api event handlers and communicates directly though react state setters of some top-level component. Not a single useEffect needed.
Besides, router doesn't usually send you anything. It just sets props on your components according to url.
You don't need useEffect() to react to anything. React itself reacts to state and props change.
You'll do yourself a favor if you ban yourself from using state setters inside useEffect(). Try it.
One benefit is performance. useEffect() causes cascading updates when it alters state.
The other is that it's way harder for your code to turn into spaghetti if you don't sidestep the whole concept of React where raw events trigger global state updates which causes react to do automatic re-render of UI which provides user with means of generating events. React should have one large loop, not multitude of small ad-hoc ones built on the side with useEffect().