dispatch while render? #1943
-
The React documentation suggests that, in some cases, it's better to call |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
No, never. The use case of calling With Redux, on the hand, dispatching an action while rendering is most definitely a side effect. The Redux store gets updated immediately, and that is an externally visible (across the app) change. Moreover, dispatching actions normally causes Redux-connected components to queue a re-render... and React will throw errors if component B has a render queued up while it's in the middle of rendering component A. So, no, don't ever dispatch actions in the middle of rendering a React component :) |
Beta Was this translation helpful? Give feedback.
No, never.
The use case of calling
setState()
while rendering only works because React special-cases that exact behavior. If it detects that you tried to do asetState()
while rendering, it queues up that state update and immediately, synchronously re-runs the rendering for that component before continuing. That means that conceptually this can sorta be seen as "not actually a side effect", because the behavior is never visible to the outside world (similar to creating a new object/array in a function, mutating it, and then returning it - no one else ever saw it being mutated, so it's okay in that case).With Redux, on the hand, dispatching an action while rendering is most definitely a s…