Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Optimize Expensive Computations in Recompose

    Tim KindbergTim Kindberg

    Learn how to use the 'withPropsOnChange' higher order component to help ensure that expensive prop computations are only executed when necessary. Simply specify which props are “expensive” and provide a factory function for those props.

    reactReact
    ^16.0.0
    recomposeRecompose
    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

    00:00 I have a Fibonacci component. It displays a computation result depending on the depth passed in. I have a little example app where I can change the depth or the size or the color of my component.

    00:14 Every time a prop changed, whether it was depth, size or color, the Fibonacci was computed. I'd rather not compute this result every time a prop changed. I'd like to change this so it just gets the result and displays it directly.

    00:29 I'm going to do the work in a new higher order component called LazyResult(). LazyResult is going to make use of the width props onChange higher-order component from Recompose. It takes in two params.

    00:50 The first param is an array of prop names that we want to wait for changes in. We only want to recalculate the result when the depth changes. The next param is a prop creator. It takes in the owner props, and it has to return a prop object to merge with the owner props.

    01:11 We'll take in the depth, and we'll return a result that contains the Fibonacci computation. When I refresh, we'll see the computed number change every time I change the depth. Now, when I change the size or the color, the computed number doesn't go up.

    Discuss

    Discuss