this is more of a question then an actual issue regarding performace
talwaserman opened this issue · 1 comments
talwaserman commented
i see that like any usage of contextAPI, each child that is under the provider is getting rendered.
i found that if i wrap the functions that are under that provider with React.memo it will prevent unneeded renders
was wondering what you think about this, did constate handle this issue? i could not find in the docs.
This is the code change:
const Button = React.memo(() => {
// 3️⃣ Use container context instead of custom hook
// const { increment } = useCounter();
const { increment } = useContext(CounterContainer.Context);
return <button onClick={increment}>+</button>;
})
const Count() = React.memo(() => {
// 4️⃣ Use container context in other components
// const { count } = useCounter();
const { count } = useContext(CounterContainer.Context);
return <span>{count}</span>;
}
diegohaz commented
Enhancing a component with React.memo
makes it render only when its props change. It doesn't work when a component is using useContext
underneath (like Button
and Count
) because it's relying on a state that doesn't come from props.
But you can use React.memo
on other (pure) components inside the Provider if you're having performance issues.