frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

169 - re-render 2 - react

Open jsartisan opened this issue 1 year ago • 0 comments

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;

jsartisan avatar Sep 09 '24 06:09 jsartisan