Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

reactjs - Why is my component rendering when useState is called with the same state?

I have a simple functional component with a boolean state. And buttons to change the state.

It is initially set to true so when I press the true-button, it does NOT render.

But if I press the false-button, it re-renders AND if I press false-button AGAIN, it will re-render even though the state is already set to false..

Could someone explain why the component re-renders when the state changes to the exact same state? How to prevent it from re-rendering?

import React, {useState} from 'react';

const TestHooks = () => {
    const [state, setState] = useState(true);
    console.log("rendering..", state);
    return(
        <div>
            <h1>{state.toString()}</h1>

            <button onClick={() => setState(true)}>true</button>

            <button onClick={() => setState(false)}>false</button>
        </div>
    )
}

export default TestHooks;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the react docs :

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo.

So your component will not re-render every time setState is called with the same state. It will re-render only 2 times and then bail out. That's just how react works and that should not be a concern except if you're doing some heavy calculations in the render method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...