调用this.setState({})是否必然触发组件重渲染?遗留代码场景问询
this.setState({}) always force a component re-render? Hey there, great question—this is a super common trick (and source of confusion) in React legacy code! Let’s break down when it does and doesn’t trigger a re-render.
First, the default scenario:
- In a regular class component (not extending
PureComponent), callingthis.setState({})will almost always trigger a re-render. React doesn’t do a shallow comparison of state changes in standard class components—so even an empty object tells React, "Something might have changed, let’s re-render." That’s exactly why that comment says "Force update"—it’s a quick way to kick off a re-render when you know external state (like a variable outside React’s state system) changed but React isn’t picking up on it.
But there are key cases where it WON’T cause a re-render:
- If your component uses
PureComponent:React.PureComponentautomatically does a shallow comparison of previous and new state/props. Since you’re passing an empty object,prevStateand the new empty state are shallowly equal—so React skips the re-render entirely. - If you’ve overridden
shouldComponentUpdate: If you’ve written a customshouldComponentUpdate(nextProps, nextState)method that returnsfalsewhennextStateis an empty object, React will honor that and skip re-rendering. This is how you manually control re-render logic. - For function components with
React.memo: While your question focuses on class components (since you’re usingthis.setState), it’s worth noting: if you have a function component wrapped inReact.memo(which does shallow prop comparisons), and you useuseStateto set an empty object that’s identical to the current state, React will skip re-rendering too.
One last detail: Even when setState({}) does trigger a re-render, React might still optimize the DOM update. If the virtual DOM comparison shows no changes to the actual UI, React won’t touch the real DOM—but the component’s render() method (or function component body) will still run.
So to wrap it up: No, this.setState({}) doesn’t always cause a re-render. It depends on whether your component is set up to do shallow state checks, or if you’ve customized the re-render logic.
内容的提问来源于stack exchange,提问作者BruceM

