diegohaz / constate

React Context + State
https://codesandbox.io/s/github/diegohaz/constate/tree/master/examples/counter
MIT License
3.93k stars 90 forks source link

this is more of a question then an actual issue regarding performace #71

Closed talwaserman closed 5 years ago

talwaserman commented 5 years ago

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 5 years ago

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.