Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Memo Renders Every Time with same given props

Tags:

reactjs

I tried to use React.memo in my functional component . It takes props from parent components. But i pass the same props to my 'memo' component.It renders every time.Same thing happened when i use React.Purecomponent.But When I use shouldcomponentupdate rerender did not happens: Why?

I have a toggle variable in my initial State .

enter image description here when i resized window handleResize called and my header reseted.This mean my toggle false is now ]

enter image description here .I passed toggle variable to my child component .

enter image description here And then i take it from props.

enter image description here .. Sorry i have some typing mistakes in this question

like image 354
Khoren Grigoryan Avatar asked Feb 15 '19 10:02

Khoren Grigoryan


1 Answers

You are passing a new toggleHamburger prop every time.

In fact this is the most common performance killer in React apps I have seen. Passing a new closure as an event handler / callback each time.

To solve this issue, I would recommend the useCallback() hook, or, in your case a method, as the outer component is a class:

class ... {
  toggleHamburger = () => this.setState(({toggle}) => ({toggle: !toggle}));
  ...
    <HamburgerButton toggleHamburger={this.toggleHamburger} />
}

A component wrapped with React.memo() will only render once if called with the same props:

const Comp = React.memo(props => {
  console.log('Rendering...');
  return props.a;
});

const props = {a: 1};
const at = document.getElementById('app');
render();
render();
render();

function render() {
  console.log('Called render()'); 
  ReactDOM.render(<Comp {...props} />, at);
}
<div id="app"></div>
<script src="//unpkg.com/react/umd/react.production.min.js"></script>
<script src="//unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
like image 162
ᅙᄉᅙ Avatar answered Nov 02 '22 12:11

ᅙᄉᅙ