Junior — Senior
Optimization and fixing state initialization in React component
livecode
Task condition
In the example below, a heavy function is called during component mounting, causing each render to block the UI for several seconds. Additionally, the button handler works incorrectly because it uses outdated value. You need to fix the state initialization by applying the lazy version of useState, and also correct the counter increment.
import React, { useState } from "react";
export default () => <div>Clicker</div>;
const computeHeavy = (initial) => {
// hard calculations
// 10sec
};
const LazyComponent = (props) => {
const [value, setValue] = useState(() => computeHeavy(props.initial));
return (
<>
{value}
<button onClick={() => setValue((prev) => prev + 1)}>
Increment
</button>
</>
);
};