--- id: 5a24c314108439a4d4036180 title: Optimize Re-Renders with shouldComponentUpdate challengeType: 6 isRequired: false videoUrl: '' localeTitle: Otimizar Re-Renders com shouldComponentUpdate --- ## Description
Até agora, se algum componente receber um novo state ou novos props , ele se renderiza novamente e a todos os seus filhos. Isso geralmente está bem. Mas o React fornece um método de ciclo de vida que você pode chamar quando os componentes filhos receberem novos state ou props e declarar especificamente se os componentes devem ser atualizados ou não. O método é shouldComponentUpdate() e leva nextProps e nextState como parâmetros. Esse método é uma maneira útil de otimizar o desempenho. Por exemplo, o comportamento padrão é que seu componente seja renderizado novamente quando receber novos props , mesmo que os props não tenham sido alterados. Você pode usar shouldComponentUpdate() para evitar isso, comparando os props . O método deve retornar um valor boolean que informa ao React se deve ou não atualizar o componente. Você pode comparar os props atuais ( this.props ) com os próximos props ( nextProps ) para determinar se você precisa atualizar ou não e retornar true ou false acordo.
## Instructions
O método shouldComponentUpdate() é adicionado em um componente chamado OnlyEvens . Atualmente, este método retorna true então o OnlyEvens re-renderiza toda vez que recebe novos props . Modifique o método para que OnlyEvens atualizado somente se o value de seus novos suportes for par. Clique no botão Add e observe a ordem dos eventos no console do seu navegador enquanto os outros ganchos do ciclo de vida são acionados.
## Tests
```yml tests: - text: O componente Controller deve renderizar o componente OnlyEvens como um filho. 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: O método shouldComponentUpdate deve ser definido no 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: O componente OnlyEvens deve retornar uma tag h1 que renderiza o valor 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 deve renderizar novamente quando nextProps.value for 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 // solution required ```