Member-only story
React — more interview questions…
How would you handle a controlled component in a React form that should only update the input value when the “Enter” key is pressed?
4 min readSep 8, 2024
import React, { useState } from 'react';
function ControlledInput() {
const [value, setValue] = useState('');
const [submittedValue, setSubmittedValue] = useState('');
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
setSubmittedValue(value);
}
};
return (
<div>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={handleKeyDown}
/>
<p>Submitted Value: {submittedValue}</p>
</div>
);
}
How would you prevent unnecessary re-renders in deeply nested child components, where props might not always change?
What to look for: Understanding of React.memo
, useMemo
, and useCallback
to avoid unnecessary re-renders.
import React, { useState, useCallback, memo } from 'react';
const ChildComponent = memo(({ onClick }) => {
console.log('Child re-rendered');
return <button onClick={onClick}>Click Me</button>;
});
function ParentComponent() {
const [count, setCount] = useState(0);
const [otherState, setOtherState] = useState(false);
const handleClick = useCallback(() => {
setCount((prevCount) => prevCount + 1);
}, []); // Function won't change unless needed…