Instructor: One more thing we need to consider in our use of context with our toggle compound components is our use of the value prop for our provider. With the way that the provider works, any time the value prop changes, it's going to re-render all consumers, so our compound components.
Because the way that we're setting this value, the value prop actually changes every single render. We can visualize that here, if we extract this to a value object. We can see clearly that this value object is getting created every single time this render function is run.
In our simple use case, the only time this render method will be run is when the on state changes, because we have no other mechanism for re-rendering the application. In a real application, the toggle component could be re-rendered anytime this usage component is re-rendered.
Whether or not the on state has changed, our toggle provider is going to re-render all of the consumers because the value object is brand new on every render. This could lead to a performance bottleneck, and so it'd be nice to avoid this.
What we really want is the value to only be updated when the state is updated. Something we could do is add the toggle function to our state, and then we'll have to move that below the definition of the toggle function.
Then, instead of this value object, we could provide all of state. This has the effect of providing the exact same object on every render except when the state is being updated, which is exactly what we want.
It might feel a little awkward to provide an event handler in state, and normally, you wouldn't want to do this. In the case of context, this is a good trade-off to make in favor of avoiding unnecessary re-renders. With that, our toggle button is still working.