Junior — Senior
Review and correction of React component: correct use of useLayoutEffect and useCallback
livecode
Task condition
It is necessary to check and improve the React component, identifying errors in the use of hooks useLayoutEffect and useCallback, as well as eliminating potential memory leaks, unnecessary event handlers, and incorrect JSX rendering.
const reviewComponent = () => {
const [counter, setCounter] = React.useState(1);
const [list, setList] = React.useState([{ id: 1 }]);
React.useLayoutEffect(() => {
document.addEventListener("click", () => {
setInterval(() => console.log(counter), 1000);
});
});
const handleClick = React.useCallback(() => {
setCounter(counter + 1);
setList([...list, { id: counter + 1 }]);
});
return (
<React.Fragment>
<ul>
{list.map((item) => (
<li key={item.id}>{item.id}</li>
))}
</ul>
<button onClick={() => handleClick()}>add one</button>
</React.Fragment>
);
}