Middle+
Refactor the component that renders a random number (from Promise) and the scroll position. Find the issues and fix them.
sobes.tech AI
Answer from AI
The main issues with a component that renders a random number from a Promise and manages scroll position are usually related to:
- Running asynchronous operations directly in the component body, leading to infinite re-renders.
- Not cleaning up event listeners (e.g., for scroll), causing memory leaks.
- Incorrect state management.
An example of a corrected React component with hooks:
import React, { useState, useEffect } from 'react';
function RandomNumberAndScroll() {
const [randomNumber, setRandomNumber] = useState(null);
const [scrollPosition, setScrollPosition] = useState(window.scrollY);
useEffect(() => {
// Get a random number from Promise once on mount
const fetchRandomNumber = async () => {
const number = await new Promise(resolve => {
setTimeout(() => resolve(Math.floor(Math.random() * 100)), 500);
});
setRandomNumber(number);
};
fetchRandomNumber();
}, []); // empty dependency array — called once
useEffect(() => {
const handleScroll = () => {
setScrollPosition(window.scrollY);
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return (
<div>
<p>Random number: {randomNumber !== null ? randomNumber : 'Loading...'}</p>
<p>Scroll position: {scrollPosition}px</p>
</div>
);
}
export default RandomNumberAndScroll;
Key points:
- The asynchronous call is wrapped in
useEffectwith an empty dependency array to prevent it from running on every render. - The scroll event handler is added and removed correctly to avoid leaks.
- States are updated via
useState.
This ensures stable and efficient component operation.