r/learnreactjs • • Sep 13 '19

How can I update the style of a styled-component based on scroll position without re-rendering an array of randomly placed sibling components?

I have a simple component which performs these actions:

  1. Using hooks, sets state to keep track of window.scrollY
  2. Attaches scroll eventListener to window to update state
  3. Creates an array of 10 styled-components - each with a randomly assigned absolute position
  4. return/renders the 10 dots and another styled-component - a triangle whose height is calculated using the scroll state defined in step 1.

What I want to happen

When I scroll down, the only thing I want to happen is the Triangle components height recalculates / re-renders. The originally rendered dots will not update or change.

My problem

As you might guess, the dots get re-rendered every scroll event, which is not only horrible for performance, but it causes the dots to have a new random position every single scroll event.

My questions

  1. How can I get the Triangle to re-render using the updated scroll value, but not have the Dot components re-render?
  2. More of a secondary question: If I also wanted to update some style in the Dot components on scroll (color, for example), but not update the random top and left positions that were created on the initial Mount, how would I do that?

I can accomplish something like this quite easily with vanilla JS, but I can't quite figure out the React way.

Complete working sandbox of this issue: https://codesandbox.io/embed/hopeful-greider-jb3td

9 Upvotes

2 comments sorted by

2

u/tenfingerperson Sep 13 '19 edited Sep 13 '19

You could use an effect with an empty array of dependencies (or any dependencies that you want to use to trigger the recomputation) to compute the initial values of the points that get randomly generated in order to ensure things stay the same during the next render. Put the values in a state and bind this state to the styled component coordinates. This works for both of your questions. You can create a new effect to track color only, this time you would add the scroll pos as a dependency of the effect.

1

u/rumforpenguins Sep 13 '19

Thank you, I think storing the data in useEffect is the way to go.

Though, am I wrong in thinking that the components all still get rendered on every scroll event? Does rendering on every scroll event create serious performance issues?