Как убрать повторный рендер элемента? React
Есть вот такой маленький пример компонента App:
import React from 'react';
const Child = () => <div>I'm Child</div>
const MChild = React.memo(Child);
const Parent = (props) => <div>{props.children}</div>
const MParent = React.memo(Parent)
const App = () => {
const [count, setCount] = React.useState(0);
return(
<div>
<button onClick={()=>setCount(count+1)}>{count}</button>
<MParent>
<MChild />
</MParent>
</div>
)
};
export default App;
Если нажать на кнопку и использовать react devtools, то можно увидеть, что компонент MParent повторно рендерится по причине измененного children. Вопрос можно ли как-то избавиться от повторного рендеринга MParent?
Ответы (1 шт):
Автор решения: ksa
→ Ссылка
Я проверил пример ТСа - у меня получается всего один рендер...
const Child = () => <div>I'm Child</div>
const MChild = React.memo(Child);
const Parent = (props) => {
console.log('MParent')
return <div>{props.children}</div>
}
const MParent = React.memo(Parent)
const App = () => {
const [count, setCount] = React.useState(0);
return(
<div>
<button onClick={()=>setCount(count+1)}>{count}</button>
<MParent>
<MChild />
</MParent>
</div>
)
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<div id='root'></div>