Controlled Input In Memo Child
ReactJS
Hard
7 views
Problem Description
Keep a fast input responsive by isolating re-renders in a memo child.
Output Format
Render a React component.
Constraints
Store input state inside a memoized component to reduce parent re-renders.
Official Solution
import React, { memo, useState } from 'react';
const SearchBox = memo(function SearchBox({ onSearch }) {
const [value, setValue] = useState('');
function submit(e) {
e.preventDefault();
onSearch(value.trim());
}
return (
<form onSubmit={submit} style={{ display: 'flex', gap: 10 }}>
<input value={value} onChange={(e) => setValue(e.target.value)} placeholder='Search meetcode...' style={{ flex: 1, padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<button type='submit' style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Go</button>
</form>
);
});
export default function App() {
const [term, setTerm] = useState('');
const [count, setCount] = useState(0);
return (
<div style={{ padding: 16, width: 560 }}>
<h2 style={{ marginTop: 0 }}>Isolate input</h2>
<SearchBox onSearch={(t) => setTerm(t)} />
<div style={{ marginTop: 10, color: '#555' }}>Last search: {term || '(none)'}</div>
<button type='button' onClick={() => setCount((c) => c + 1)} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Parent updates: {count}</button>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!