UPDATE 25.10.2018
Since React 16.6, you can use React.memo for functional components to prevent re-render, similarly to PureComponent
for class components:
const MyComponent = React.memo((props) => {
return (
/* markup */
);
});
Also, memo does internal optimization.
And unlike a userland memo() higher-order component implementation, the one built into React can be more efficient by avoiding an extra component layer.
Blockquote
OLD ANSWER
Yes, they always re-render 1 (unless you use React.memo as explained above) if setState()
is called in the component itself or one of its parents, because functional stateless components don't carry a shouldComponentUpdate. In fact, each React component is being re-rendered1 unless they implement shouldComponentUpdate
.
Important to note is that calling render()
doesn't mean that DOM Nodes are being manipulated in any way. The render
method just serves the diff algorithm to decide which DOM Nodes need to really be attached / detached. Note that render()
is not expensive, it's the DOM manipulations that are expensive. They are executed only if render()
returns different virtual trees.
From React's documentation
Just to be clear, rerender in this context means calling render for all components, it doesn’t mean React will unmount and remount them. It will only apply the differences following the rules stated in the previous sections.
Just don't worry and let render()
be called unless your component is huge, then you're better off with stateful Component that implements shouldComponentUpdate()
.
Look here for an interesting discussion.
1 means that render()
function of the component is called, not that the underlying DOM node is being manipulated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…