Improve

React
Performance

But I've heard React is fast!

Simple to write, easy to mess up

React Component

  • Component
  • PureComponent
  • Function Component
  • React.memo ( Function Component )

shouldComponentUpdate

  • Component => true
  • PureComponent => when props/state change

Why Did You Render ??

We can't improve what we don't measure

why-did-you-render

React DevTools Profiler

Common Re-render Scenarios

Parent Re-render

const ParentComponent = props => (

    <div>

        <Demo foo={1}/>

    </div>

)

  • Don't update parent somehow
  • Make child a pure component

Props Equal by Value

<Demo foo={{bar:123}}/>

 

  • prevProps !== nextProps
  • prevProps.foo !== nextProps.foo
  • prevProps.foo.bar === nextProps.foo.bar
  • Pass in the same object if value not change

Props Equal by Value

❌
<Demo foo={this.props.bar || []}/>

 

const EMPTY_ARR = [];
<Demo foo={this.props.bar || EMPTY_ARR}/>

Props Equal by Value


const mapStateToProps = state => ({

    bar: getSomeValue(state) || { },

})

 

const EMPTY_OBJ = {};

const mapStateToProps = state => ({

    bar: getSomeValue(state) || EMPTY_OBJ,

})

Callback change


<Demo onClick={
() => doSomething()}/>

 

const onClick = useCallback(

    () => doSomething(),

    [foo, bar]

);

<Demo onClick={onClick}/>

Optimization

The difference between them is that

React.Component doesn’t implement shouldComponentUpdate(),

but React.PureComponentimplements it with a

shallow prop and state comparison.

React components for efficiently rendering

large lists and tabular data

export const getTotalUnreadCount = createSelector(

    // dependencies

    ({ state }) => state.messages.sessions,

    ({ state }) => state.messages.selectedSession,

    ({ state }) => state.messages.muted,

    ({ state }) => state.messages.unreadCounts,

    ({ state }) => state.onlineStatus.onlineStatus,

    ({ state }) => state.notification.settings,

 

    // heavy computation

    (sessions, selectedSession, muted, ...) => {

        return calculateTotalUnreadCount( ... );

    }

);

✔Shallow Compare

Space & Time

Improve React-Redux Performance

By Oscar Tong

Improve React-Redux Performance

Just another react-redux performance slides

  • 619