简体   繁体   中英

React Hooks: how to avoid re-rendering of component on another state change?

Here is my code.

const test = () => {
    const [state, setState] = useState(0)
    const clickOne = () => setState(1)
    const clickTwo = () => setState(2)

    return (
        <>
        <div className="title">
            <h1>Title</h1>
        </div>
        <div className="buttons">
            <button onClick={clickOne}>1</button>
            <button onClick={clickTwo}>2</button>
        </div>
        <div className="content">
            {state === 0 ? <div>click!</div> : state === 1 ? <div>1</div> : <div> 2 </div>}
        </div>
        </>
    )
}

What I'm trying here is to only re-render "#buttons" area and "#content" area when <button> in "#buttons" area is clicked.

As of now, "#title" area is re-rendered every time the button is clicked. How can I force "#title" area not to be re-rendered? Thanks.

Use different components and React.memo

const Header = React.memo(() => {
  return (<div className="title">
        <h1>Title</h1>
    </div>)
});

const test = () => {
const [state, setState] = useState(0)
const clickOne = () => setState(1)
const clickTwo = () => setState(2)

return (
    <>
    <Header/>
    <div className="buttons">
        <button onClick={clickOne}>1</button>
        <button onClick={clickTwo}>2</button>
    </div>
    <div className="content">
        {state === 0 ? <div>click!</div> : state === 1 ? <div>1</div> : <div> 2 </div>}
    </div>
    </>
)
}

From the docs:

If your component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result.

But note that you can't use it to rely on the render prevention, rather it's just optimization

You should split "#title into a component.

const Title = () => {
  return (
    <div className="title">
      <h1>Title</h1>
    </div>
  );
};

const Test = () => {
  const [state, setState] = useState(0);
  const clickOne = () => setState(1);
  const clickTwo = () => setState(2);

  return (
    <>
      <div className="buttons">
        <button onClick={clickOne}>1</button>
        <button onClick={clickTwo}>2</button>
      </div>
      <div className="content">
        {state === 0 ? <div>click!</div> : state === 1 ? <div>1</div> : <div> 2 </div>}
      </div>
    </>
  );
};

And using it in the parent component

<Title />
<Test />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM