This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Prevent Unnecessary Rerenders of Compound Components using React Context

    Kent C. DoddsKent C. Dodds

    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.

    reactReact
    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    Instructor: 00:00 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.

    00:17 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.

    00:32 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.

    00:47 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.

    01:01 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.

    01:12 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.

    01:24 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.

    Discuss

    Discuss