Is it correct that this.setState in class components always cause a
re-render, even when the new state value is identical to the previous?
If you set a valid value apart from returning null within setState, a re-render will always be triggered by react in a class component unless your component is a PureComponent or you implement shouldComponentUpdate
Is it correct that in function components with hooks, setState from
useState only causes a re-render if the state value is different from
the previous value?
For a functional component using useState
hook, the setter if called with the same state will not trigger a re-render. However for an occasional case if the setter is called immediately it does result in two renders instead of one
Is setting state with this.setState inside the render method of a
class component, the same as setting state inside the function body of
a function component with hooks?
Techincally yes, setting a state directly in render method will cause the function to trigger re-render in case of class component causing an infinite loop which is the case for functional components provided the state values are different. Regardless of that, it will still cause an issue because any other state update will be reverted back due to functional component calling state update directly
In a class component, if we set state in the render method an infinite
loop will occur. This is because the class component does not care
that the new state is the same as the previous state. It just keeps
re-rendering on every this.setState.
Yes, hence its recommended not to call setState directly in render
In a function component with hooks however, setting state inside the
function body (which runs at re-render similarly to the render method
in class components) would not be an issue, because the function
component just bails out of re-renders when it sees that the state is
identical to the previous state.
Not 100% true, since you can trigger state update using previous value such that the previous and current value are not same.For example
setCount(count => count + 1);
In such a case, you component will still fall in an infinite loop
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…