useCallback Stable Handler
ReactJS
Hard
5 views
Problem Description
Use useCallback to keep a stable function reference for a memoized child.
Output Format
Render a React component.
Constraints
Wrap handler in useCallback and memoize child component.
Official Solution
import React, { useCallback, useState } from 'react';
const Child = React.memo(function Child({ onPing }) {
return (
<button type='button' onClick={onPing} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>
Ping
</button>
);
});
export default function App() {
const [pings, setPings] = useState(0);
const [count, setCount] = useState(0);
const onPing = useCallback(() => setPings((n) => n + 1), []);
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode callbacks</h2>
<Child onPing={onPing} />
<div style={{ marginTop: 10, color: '#555' }}>Pings: {pings}</div>
<button type='button' onClick={() => setCount((n) => n + 1)} style={{ marginTop: 12, padding: '8px 12px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Unrelated state ({count})</button>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!