Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Prevent Unnecessary Rerenders of Compound Components using React Context


    Due to the way that React Context Providers work, our current implementation re-renders all our compound component consumers with every render of the <Toggle /> which could lead to unnecessary re-renders. Let's fix that by ensuring that the value prop we pass to the <ToggleContext.Provider /> is only changed when the state changes.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.