Optimizing Rendering React Components

MobX is very fast, often even faster than Redux. But here are some tips to get the most out of React and MobX.

Use Many Small Components

@observer components will track all values they use and re-render if any of them changes. So the smaller your components are, the smaller the change they have to re-render; it means that more parts of your user interface have the possibility to render independently of each other.

Render Lists in Dedicated Components

This is especially true when rendering big collections. React is notoriously bad at rendering large collections as the reconciler has to evaluate the components produced by a collection on each collection change. It is therefore recommended to have components that just map over a collection and render it, and rendering nothing else:

@observer class MyComponent extends Component {
    render() {
        const {todos, user} = this.props;
        return (<div>
            {user.name}
            <TodosView todos={todos} />
        </div>)
    }
}

@observer class TodosView extends Component {
    render() {
        const {todos} = this.props;
        return <ul>
            {todos.map(todo => <TodoView todo={todo} key={todo.id} />)}
        </ul>)
    }
}

Don't Use Arrays Indexes as Keys

Don't use array indexes or any value that might change in the future as key. Generate id's for your objects, if needed.

De-Reference Values Late

When using mobx-react, it is recommended to de-reference values as late as possible. This is because MobX will re-render components that de-reference observable values automatically. If this happens deeper in your component tree, less components have to re-render.

<DisplayName person={person} />

A change in the name property will trigger the DisplayName to re-render. To have the best of both worlds, consider making smaller components.

const PersonNameDisplayer = observer(({ props }) => 
    <DisplayName name={ props.person.name } />);

Bind Functions Early

This tip applies to React in general and libraries using PureRenderMixin especially. Try to avoid creating new closures in render methods.

render() {
    return <MyWidget onClick={this.handleClick} />
}

handleClick = () => {
    alert('hi')
}

results matching ""

    No results matching ""