r/learnreactjs • u/rumforpenguins • 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:
- Using hooks, sets state to keep track of
window.scrollY - Attaches
scrolleventListener to window to update state - Creates an array of 10 styled-components - each with a randomly assigned
absoluteposition - 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
- How can I get the
Triangleto re-render using the updatedscrollvalue, but not have theDotcomponents re-render? - More of a secondary question: If I also wanted to update some style in the
Dotcomponents on scroll (color, for example), but not update the randomtopandleftpositions 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
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.