Junior — Middle+
Enhancing React component efficiency through lazy state initialization
livecode
Task condition
In this example, the component's state is filled immediately by calling a resource-intensive function on every render. It is necessary to rewrite the component so that the heavy function is computed only once — during the initial mounting — while allowing the user to increase the counter value via a button.
const computeRandom = total => {
return Math.floor(Math.random() * total);
};
const LazyInit = props => {
const [value, setValue] = useState(computeRandom(props.count));
return (
<>
{value}
<button onClick={() => setValue(prev => ++prev)}>Increment</button>
</>
);
};