From 4b6b46b4a8abf8428b268a94e1b610d05883d0a8 Mon Sep 17 00:00:00 2001 From: Nathan Wenneker Date: Thu, 5 Nov 2015 18:21:28 -0700 Subject: [PATCH] Use shouldRenderComponent to reduce rendering and recalculation By creating a component that only takes relevant properties that would cause a recalculation, we're free to redefine shouldRenderComponent to compare object equality of all of the props. If any props change, render (and recalculate); otherwise, no need to render or recalculate. This is similar to memoization, but using `react` lifecycle. In order for this approach to work, you have to create a component that _doesn't_ take an unrelated prop (i.e. `currentTheme`). --- components/TodoList.js | 23 ++++++++++++++++++++++- containers/App.js | 21 ++++++--------------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/components/TodoList.js b/components/TodoList.js index d4796cb..2a39ffc 100644 --- a/components/TodoList.js +++ b/components/TodoList.js @@ -1,11 +1,31 @@ import React, { Component, PropTypes } from 'react' import Todo from './Todo' +import { VisibilityFilters } from '../actions' export default class TodoList extends Component { + + shouldComponentUpdate(nextProps, nextState) { + return nextProps.filter !== this.props.filter || nextProps.todos !== this.props.todos; + } + + visibleTodos() { + return function(todos, filter) { + console.log("Recalculating visibleTodos"); + switch (filter) { + case VisibilityFilters.SHOW_ALL: + return todos; + case VisibilityFilters.SHOW_COMPLETED: + return todos.filter(todo => todo.completed) + case VisibilityFilters.SHOW_ACTIVE: + return todos.filter(todo => !todo.completed) + } + }(this.props.todos, this.props.filter); + } + render() { return (