Coder Social home page Coder Social logo

noamelb / shouldcomponentupdate-children Goto Github PK

View Code? Open in Web Editor NEW
268.0 10.0 10.0 50 KB

React "Shallow Equal" HOC implementation to optimize shouldComponentUpdate with children / React elements ๐Ÿ‡โžฐ

License: MIT License

JavaScript 100.00%
shouldcomponentupdate hoc react-elements props react

shouldcomponentupdate-children's Introduction

shouldComponentUpdate-Children

A PureComponent alternative that will actually improve your application performance!

"Shallow Equal" HOC implementation to optimize shouldComponentUpdate with children / React elements.

See live example here: codepen.io/NoamELB/pen/RLoxLv

Usage

Install

npm i -S shouldcomponentupdate-children

Option 1: As an HOC when exporting a component:

import {useShallowEqual} from 'shouldcomponentupdate-children';

class MyComponent extends React.Component {
    ....
}
const MyPerformantComponent = useShallowEqual(MyComponent);

export default MyPerformantComponent;

Option 2: As an HOC when importing a component:

import {useShallowEqual} from 'shouldcomponentupdate-children';
import MyComponent from './my-component';

const MyPerformantComponent = useShallowEqual(MyComponent); // use it just like you would use MyComponent

Option 3: As the shouldComponentUpdate implementation

import {shallowEqual} from 'shouldcomponentupdate-children';

class MyComponent extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
        return shallowEqual(this.props, nextProps, this.state, nextState);
    }
}
export default MyComponent;

The Problem

React will create a new instance of a React Element on each render, so generic implementations to shouldComponentUpdate will return true even if nothing had changed!

Basically, this simple shouldComponentUpdate implementation:

return this.props.children !== nextProps.children;

is almost as good as writing:

return true;

See live example here: codepen.io/NoamELB/pen/RLoxLv

Read more about it here: https://medium.com/myheritage-engineering/how-to-greatly-improve-your-react-app-performance-e70f7cbbb5f6

Our Solution

We created an HOC which uses Inheritance Inversion to extend components with a generic shouldComponentUpdate functionality.

Our generic shouldComponentUpdate implementation does the following:

  • execute the wrapped component's shouldComponentUpdate and continue only if returned true.
  • shallow equal this.state vs next state and return true if not equal.
  • shallow equal all this.props vs next props, but skip React Elements. return true if not equal.
  • if reached here - returns false

But isn't this means that if any React Element is actually changing then my component won't render?

Yes, but that is the whole point. React Elements are not something you can rely upon when implementing shouldComponentUpdate!

In order to tell a component that it should render - you can change any non-React-Element prop to indicate a state change (this can be a designated prop just for that or a prop that is actually in use inside the component).

Q&A

Why use shouldComponentUpdate?

Performance. If the change in state or props does not affect your component, you can tell React. React will not re-render your component for no reason in that case. Read more: https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate

How to use shouldComponentUpdate?

MyClass extends React.Component {
    ...
    shouldComponentUpdate(nextProps, nextState) {
       // return true or false
    }
}

It's common to want to re-render when either the state or any prop has changed - so react created a class that does it for us:

MyClass extends React.PureComponent {
    ...
    // don't need to implement shouldComponentUpdate
}

Read more: https://facebook.github.io/react/docs/react-api.html#react.purecomponent

What's the problem with PureComponents?

If "children" (or any other prop) is a React element or an array, it will send a new instance every time. This means that in most cases, the following check will always be true:

this.props.children !== nextProps.children

The result is that our component will render even if our prop didn't actually change.

The solution - shouldComponentUpdate-Children

Wrap your components with this HOC and it will perform a wiser shallow equal check. It will skip props that would have always returned true, regardless of their value:

const MyPerformantComponent = useShallowEqual(MyComponent);

How do you determine that a prop is a React Element

  1. Any prop that returns true for React.isValidElement(prop).
  2. Any array prop that have at least one item which returns true for React.isValidElement(prop[i])

Why implement as an HOC?

HOC is very useful in this specific case of Inheritance Inversion, you can use it on the outside when importing.

Let's see some nice examples of when to use on the outside:

  • Using a vendor component that has performance issues? Just wrap it with the HOC after the import.
  • Implementing shouldComponentUpdate in a given component is a refactor headache? HOC to the rescue.
  • shouldComponentUpdate is already implemented but not good enough for your usage? you know who to call.

By tha way, we exports all of the functions from the package, so you can use them directly when implementing shouldComponentUpdate:

  • shouldComponentUpdate(nextProps, nextState) - bind the "this" to the function and just use it as your shouldComponentUpdate.
  • shallowEqual(this.props, nextProps, this.state, nextState) - same but with no need to bind anything.
  • shallowEqualWithoutReactElements(thisProps, nextProps) - the actual shallow equal implementation on the props.
  • shallowEqualState(thisState, nextState) - the actual shallow equal on the state.

License

MIT

shouldcomponentupdate-children's People

Contributors

noamelb avatar tzook avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

shouldcomponentupdate-children's Issues

Class constructor Comment cannot be invoked without 'new'

When adding the package and using the HOC on one of the components I get the following Error:

Uncaught TypeError: Class constructor Comment cannot be invoked without 'new' at new ShallowEqualEnhancer (main.bundle.js:77123) at constructClassInstance (main.bundle.js:33250) at updateClassComponent (main.bundle.js:33705) at beginWork (main.bundle.js:34095) at performUnitOfWork (main.bundle.js:36063) at workLoop (main.bundle.js:36172) at HTMLUnknownElement.callCallback (main.bundle.js:24789) at Object.invokeGuardedCallbackDev (main.bundle.js:24828) at invokeGuardedCallback (main.bundle.js:24685) at performWork (main.bundle.js:36290) main.bundle.js:31795

The above error occurred in the <ShallowEqualEnhancedComment> component: in ShallowEqualEnhancedComment (created by CommentList) in div (created by wrapperStyle) in wrapperStyle (created by wrapperStyle) ...

stack includes next.js 4 and react 16

TransformError: Couldn't find preset "es2015"

When I import the package and run the app (within Expo), I have the following message

TransformError: index.cjs.js: couldn't find preset "es2015" relative to directory .../node_modules/shouldcomponentupdate-children

I've noticed that you are not using the babel-preset-env instead, submitted PR for this, but it does not solve the problem.
my .babelrc is

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  }
}

Misleading function shallowEqual()

Hi and thank you for this HOC. I also read your article https://medium.com/myheritage-engineering/how-to-greatly-improve-your-react-app-performance-e70f7cbbb5f6
which has been pretty helpful.

I only have one question regarding the shallowEqual function:

export function shallowEqual(thisProps, nextProps, thisState, nextState) {
    return !shallowEqualState(thisState, nextState) || !shallowEqualWithoutReactElements(thisProps, nextProps);
}

Right now, it returns true when the component should update (something has changed), and false otherwise. On the other hand, shallowEqualState and shallowEqualWithoutReactElements both work in the opposite way: they return false when there's a change (something has changed), and true otherwise.

That said, shouldn't shallowEqual use logical AND instead of OR in its body? E.g.:

export function shallowEqual(thisProps, nextProps, thisState, nextState) {
    return shallowEqualState(thisState, nextState) && shallowEqualWithoutReactElements(thisProps, nextProps);
}

This way, if shallowEqual returns true, it means that the props/state are equal and that the component should not update. Whereas, if it returns false, it would mean that something has changed and the component should update.

And then, someone using shallowEqual would have to negate it in order to know that something has changed and therefore a component should update:

            ...
            if (!super.shouldComponentUpdate || super.shouldComponentUpdate(nextProps, nextState)) {
                shouldUpdate = !shallowEqual(this.props, nextProps, this.state, nextState); // If shallowEqual returns `false`, it means that the prev props or state are not equal to the next props or state and we should therefore update...
            }
            ...

What do you think?

Export non-HOC version?

I know you said in the README that you love HOCs, but I don't see the benefit of adding another level to my component tree when it's not needed. It'd be trivial to add one more little export:

export function shouldComponentUpdate(nextProps, nextState) {
    return !shallowEqualState(this.state, nextState) || !shallowEqualWithoutReactElements(this.props, nextProps);
}

Could you add it please? โค๏ธ

PS: This thing is working like magic. Much less rendering with no ill-effects so far.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.