Optimizing React Performance with Stateless Components  #reactjs #javascript
  • First, the Super Basics import React, { Component } from ‘react’ class User extends Component { render() { const { name, highlighted, userSelected } = this.props console.log(‘Hey User is being rendered for’, [name, highlighted]) return div h3 style={{fontStyle: highlighted ?
  • For example, something like this: import React, { Component } from ‘react’ class Users extends Component { constructor(props) { super(props) this.state = { otherData: null, users: [{name: ‘John Doe’, highlighted: false}] } } async componentDidMount() { try { let response = await let data = await response.json() this.setState({otherData: data}) } catch(err) { throw err } } toggleUserHighlight(user) { this.setState(prevState = { users: prevState.users.map(u = { if (u.name === user.name) { u.highlighted = !
  • import React, { PureComponent } from ‘react’ class User extends PureComponent { render() { const { name, highlighted, userSelected } = this.props console.log(‘Hey User is being rendered for’, [name, highlighted]) return div h3 style={{fontStyle: highlighted ?
  • Our first attempt at re-writing it back to a functional component but with recompose.pure looks like this: import React from ‘react’ import { pure } from ‘recompose’ const User = pure(({ name, highlighted, userSelected }) = { console.log(‘Hey User is being rendered for’, [name, highlighted]) return div h3 style={{fontStyle: highlighted ?
  • ‘italic’ : ‘normal’}} onClick={event = { userSelected() }}{name}/h3 /div }) export default User As you might notice, if you run this, the User component still re-renders even though the props (the name and highlighted keys) don’t change.

Read more


ferroariel

@ferroariel: “Optimizing React Performance with Stateless Components #reactjs #javascript” open tweet »