Prevent Unnecessary Re-render
ReactJS
Hard
5 views
Problem Description
Move inline objects outside render to avoid new references each render.
Output Format
Render a React component.
Constraints
Use constant style objects.
Official Solution
import React, { useState } from 'react';
const cardStyle = { border: '1px solid #eee', borderRadius: 14, padding: 14, width: 360 };
const Title = React.memo(function Title({ text }) {
return <h2 style={{ margin: '0 0 8px 0' }}>{text}</h2>;
});
export default function App() {
const [n, setN] = useState(0);
return (
<div style={{ padding: 16 }}>
<div style={cardStyle}>
<Title text='meetcode' />
<div style={{ color: '#555' }}>Counter: {n}</div>
</div>
<button type='button' onClick={() => setN((v) => v + 1)} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>
Add
</button>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!