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.

Answer

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 />