4 ms·
Wait so in the prop change example they are now recommending that you can update state during a component render?
by erwinh 4y ago
Wait so in the prop change example they are now recommending that you can update state during a component render?
- _thisdot 4y agoFar 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}'`
- foota 4y agoThey're referring to https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes 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"
- foota 4y agoWow, that's really weird.
- jannes 4y agoYes, 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.
- aeroaero 4y agoYep 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-mostly-complete-guide-to-react-rendering-behavior/#setting-state-while-rendering https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-...
- deleted 4y ago[deleted]
- idkwhoiam 4y agoThis 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.
- sickcodebruh 4y agoI 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.