Reputation: 43
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.
Upvotes: 2
Views: 4783
Reputation: 994
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
Upvotes: 3
Reputation: 12807
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 />
Upvotes: 0