frontend-challenges
frontend-challenges copied to clipboard
169 - re-render 2 - react
App.jsx
import { useState } from 'react';
import { MovingBlock } from "./components/moving-block";
import { VerySlowComponent } from './components/very-slow-component';
import { BunchOfStuff, OtherStuffAlsoComplicated } from './components/mocks';
export default function App() {
return (
<ScollableContentWithMovingBlock>
<VerySlowComponent />
<BunchOfStuff />
<OtherStuffAlsoComplicated />
</ScollableContentWithMovingBlock>
);
}
function ScollableContentWithMovingBlock({ children }) {
const [position, setPosition] = useState(150);
const onScroll = (e) => {
const calculated = getPosition(e.target.scrollTop);
setPosition(calculated);
};
return (
<div className="scrollable-block" onScroll={onScroll}>
<MovingBlock position={position} />
{children}
</div>
);
}
// just hard-coded approximation to demonstrate the re-renders problem
// not to be used in real code
const getPosition = (val) => 150 - val / 2;