Stable Object Props With useMemo
ReactJS
Medium
4 views
Problem Description
Pass stable object props to memoized child so it doesn’t re-render.
Output Format
Render a React component.
Constraints
Memoize objects/arrays that you pass as props.
Official Solution
import React, { memo, useMemo, useState } from 'react';
const Box = memo(function Box({ style, label }) {
return (
<div style={{ ...style, borderRadius: 14, padding: 12 }}>
<strong>{label}</strong>
<div style={{ marginTop: 6, color: '#555' }}>meetcode UI</div>
</div>
);
});
export default function App() {
const [dark, setDark] = useState(false);
const [count, setCount] = useState(0);
const cardStyle = useMemo(() => {
return {
border: '1px solid ' + (dark ? '#333' : '#eee'),
background: dark ? '#111' : '#fff',
color: dark ? '#fff' : '#124'
};
}, [dark]);
return (
<div style={{ padding: 16, width: 420 }}>
<Box style={cardStyle} label={'Count: ' + count} />
<div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
<button type='button' onClick={() => setCount((c) => c + 1)} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Increment</button>
<button type='button' onClick={() => setDark((d) => !d)} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Toggle theme</button>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!