Junior — Senior
Improving React component performance
livecode
Task condition
The task is to improve the provided React example so that the Child component does not re-render when typing in the input field.
import React from 'react';
export default function App() {
const triggerRender = useForceUpdate();
return (
<div style={{ margin: '20px', padding: '20px', border: '2px solid green' }}>
<button onClick={triggerRender}>Render</button>
<RenderCount />
<Parent />
</div>
);
}
const Parent = () => {
const [text, setText] = React.useState('');
const onInputChange = (e) => {
setText(e.target.value);
};
return (
<form style={{ margin: '20px', padding: '20px', border: '2px solid blue' }}>
Input value is: {text}
<RenderCount />
<Child onChange={onInputChange} />
</form>
);
};
const Child = ({ onChange }) => {
return (
<div style={{ padding: '20px', margin: '20px', border: '2px solid red' }}>
<input type="text" name="value" onChange={onChange} />
<RenderCount />
</div>
);
};
function RenderCount() {
const renderCount = React.useRef(1);
React.useEffect(() => {
renderCount.current += 1;
});
return (
<div style={{ marginTop: '10px' }}>
Render count: {renderCount.current}
</div>
);
}
The task is to apply appropriate techniques (such as React.memo, useCallback, etc.) so that the child component remains unchanged when the parent's input state changes.