Hacker News new | ask | show | jobs
by erwinh 1181 days ago
Wait so in the prop change example they are now recommending that you can update state during a component render?
6 comments

Yep it can be a useful pattern, but it must be in a conditional to stop an infinite loop.

This useful guide points it out as well: https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-...

I found this one very surprising. I’ve operated for years with the understanding that side-effects should never ever occur within the render flow. Complicated as hooks are, I dread having to explain the nuances of this particular one to other React devs.
Yes, and they explain it as well. Doing that leads to the component re-rendering immediately without rendering any child components.

This should be faster than useEffect which only executes after the entire render has been committed to the DOM.

This caught me off guard. I've never seen this pattern anywhere including popular 3rd party React libs. Therefore it doesn't feel right but their explanation makes sense.
Far as I see they aren't. They're recommending you don't use unnecessary state. From the example, if you have state for `firstName` and `lastName`, you don't need another state for `fullName`. Just calculate it during the render as `'${firstName} ${lastName}'`
They're referring to https://react.dev/learn/you-might-not-need-an-effect#adjusti..., where they literally call setFoor in the render method.

I guess this makes sense, but it's weird after all the "never do anything stateful in render"

Wow, that's really weird.