Next.js Discord

Discord Forum

setState calls inside component body are causing errors, how to structure components?

Answered
Satin Angora posted this in #help-forum
Open in Discord
Satin AngoraOP
For one of my components, I have two functions inside component body to work with data, and set the related state. From this functions, I'm getting the error
Warning: Cannot update a component (`HotReload`) while rendering a different component (`DashboardPanel`). To locate the bad setState() call inside `DashboardPanel`, follow the stack trace as described in...
I have readen up on this, and usually the solution is to wrap setState calls into useEffect hook; but to get an effect to fire, something must trigger it. When I press a button, the related functions get called to fetch some data, and they take parameters related to the data requested. So it can't be an effect.

How should I approach this? (I think this is more of a React question...)
Answered by Shy Albatross
definitely a React question, wrapping setState in a useEffect means deferring state mutation until after a render - it won't solve anything since the issues for you seems to be that you're updating states of multiple components at once, and those components are in a parent-child relationship
View full answer

4 Replies

Shy Albatross
definitely a React question, wrapping setState in a useEffect means deferring state mutation until after a render - it won't solve anything since the issues for you seems to be that you're updating states of multiple components at once, and those components are in a parent-child relationship
Answer
Shy Albatross
typically solving such problems in React is, rather than doing hacks, memos and effects, is taking a step back and rethinking your approach, because you can't see the forest for the trees
in general, if a interaction with a child needs to update parent's state, don't try to update 2 states at once, rather pass a function from parent to child that allows the child to update parent's state, then pass the necessary bits down to the child as props, this way you trigger a re-render of the parent (state change)that will also re-render your child (props change)
Satin AngoraOP
@Shy Albatross Thank you for your response. I am restructuring related part of my project right now, will take your advices into consideration.