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 .
when i resized window handleResize called and my header reseted.This mean my toggle false is now ]
.I passed toggle variable to my child component .
And then i take it from props.
.. Sorry i have some typing mistakes in this question
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With