Redux Bad Practices #5: New Objects On The Fly

Adam Klein
2 min readFeb 27, 2019

--

Consider the following code:

mapStateToProps = (state) => ({
currentUser: {
id: state.currentUserId, role: state.currentRole
}
})

The example above will always return a new object for currentUser and will force the component to re-render. The same idea applies to returning a new array (e.g. by using map, filter, concat), and anonymous functions.

Either pass the id and role as flat properties:

mapStateToProps = (state) => ({
currentUserId: state.currentUserId,
currentUserRole: state.currentRole
})

Or use a selector that returns currentUser from state:

mapStateToProps = (state) => ({
currentUser: selectCurrentUser(state)
})

Notice that passing an anonymous function will also create a new reference. So try to avoid code like this if you need a performant component:

<MyComp onEvent={ () => this.doSomething() } otherProps={ ... }/>

The () => doSomething() anonymous function will have a different reference each time we render MyComp, and will cause it to re-render even if it's a pure component (a component that re-renders only when state or props change).

Alternatively, you could pass a pre-bound function that is only initialized once:

bindedEventCallback = () => {}
render() {
return <MyComp
onEvent={ this.bindedEventCallback }
otherProps={ ... }/>;
}

Or use the useCallback hook that memoizes the callback:

myComp() {
const bindedEventCallback = useCallback(() => {});

return <MyComp
onEvent={ bindedEventCallback }
otherProps={ ... }/>;
}

All articles in this series:

https://medium.com/@adamklein_66511/redux-bad-practices-1-lists-as-arrays-9115ba87b0ce

https://medium.com/@adamklein_66511/redux-bad-practices-2-duplicate-code-9f2f3d774d4d

https://medium.com/@adamklein_66511/redux-bad-practices-3-nested-state-6eebf1a410df

https://medium.com/@adamklein_66511/redux-bad-practices-5-duplicate-state-996d259758e3

https://medium.com/@adamklein_66511/redux-bad-practices-6-new-objects-on-the-fly-c38b503948a5

https://medium.com/@adamklein_66511/redux-bad-practices-7-mix-ui-state-with-model-data-cdca6c8d8fd9

Originally published at 500tech.com.

--

--