--- id: 5a24c314108439a4d4036180 title: Optimize Re-Renders with shouldComponentUpdate localeTitle: Optimizar Re-Renders con shouldComponentUpdate challengeType: 6 isRequired: false --- ## Description
Hasta ahora, si algún componente recibe un nuevo state o nuevos props , se vuelve a rendir a sí mismo ya todos sus hijos. Esto suele estar bien. Pero React proporciona un método de ciclo de vida al que puede llamar cuando los componentes secundarios reciben un nuevo state o props , y declaran específicamente si los componentes deberían actualizarse o no. El método es shouldComponentUpdate() , y toma nextProps y nextState como parámetros. Este método es una forma útil de optimizar el rendimiento. Por ejemplo, el comportamiento predeterminado es que su componente se vuelve a procesar cuando recibe nuevos props , incluso si los props no han cambiado. Puedes usar shouldComponentUpdate() para evitar esto al comparar los props . El método debe devolver un valor boolean que indique a React si actualizar o no el componente. Puede comparar los props actuales ( this.props ) con los props siguientes ( nextProps ) para determinar si necesita actualizar o no, y devolver true o false consecuencia.
## Instructions
El método shouldComponentUpdate() se agrega en un componente llamado OnlyEvens . Actualmente, este método devuelve true por lo que OnlyEvens vuelve a representar cada vez que recibe nuevos props . Modifique el método para que OnlyEvens solo se actualice si el value de sus nuevos accesorios es par. Haga clic en el botón Add y observe el orden de los eventos en la consola de su navegador a medida que se activan los otros ganchos del ciclo de vida.
## Tests
```yml tests: - text: El componente Controller debe representar el componente OnlyEvens como un elemento secundario. testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find("Controller").length === 1 && mockedComponent.find("OnlyEvens").length === 1; })(), "The Controller component should render the OnlyEvens component as a child.");' - text: El método shouldComponentUpdate debe definirse en el componente OnlyEvens . testString: 'assert((() => { const child = React.createElement(OnlyEvens).type.prototype.shouldComponentUpdate.toString().replace(/s/g,""); return child !== "undefined"; })(), "The shouldComponentUpdate method should be defined on the OnlyEvens component.");' - text: El componente OnlyEvens debe devolver una etiqueta h1 que representa el valor de this.props.value . testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 1000 }); return waitForIt(() => mockedComponent.find("h1").html()); }; const second = () => { mockedComponent.setState({ value: 10 }); return waitForIt(() => mockedComponent.find("h1").html()); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === "

1000

" && secondValue === "

10

", "The OnlyEvens component should return an h1 tag which renders the value of this.props.value."); }; ' - text: OnlyEvens debería volver a generar solo cuando nextProps.value es par. testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 8 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const second = () => { mockedComponent.setState({ value: 7 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const third = () => { mockedComponent.setState({ value: 42 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(firstValue === "8" && secondValue === "8" && thirdValue === "42", "OnlyEvens should re-render only when nextProps.value is even."); }; ' ```
## Challenge Seed
```jsx class OnlyEvens extends React.Component { constructor(props) { super(props); } shouldComponentUpdate(nextProps, nextState) { console.log('Should I update?'); // change code below this line return true; // change code above this line } componentWillReceiveProps(nextProps) { console.log('Receiving new props...'); } componentDidUpdate() { console.log('Component re-rendered.'); } render() { return

{this.props.value}

} }; class Controller extends React.Component { constructor(props) { super(props); this.state = { value: 0 }; this.addValue = this.addValue.bind(this); } addValue() { this.setState({ value: this.state.value + 1 }); } render() { return (
); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js class OnlyEvens extends React.Component { constructor(props) { super(props); } shouldComponentUpdate(nextProps, nextState) { console.log('Should I update?'); // change code below this line return nextProps.value % 2 === 0; // change code above this line } componentWillReceiveProps(nextProps) { console.log('Receiving new props...'); } componentDidUpdate() { console.log('Component re-rendered.'); } render() { return

{this.props.value}

} }; class Controller extends React.Component { constructor(props) { super(props); this.state = { value: 0 }; this.addValue = this.addValue.bind(this); } addValue() { this.setState({ value: this.state.value + 1 }); } render() { return (
); } }; ```