Swizec / useDimensions

A React Hook to measure DOM nodes
596 stars 45 forks source link

If there is no way to disable "measure" on scroll wouldn't it update all child components per tick? #8

Closed jmcruzmanalo closed 5 years ago

jmcruzmanalo commented 5 years ago

Here is a sandbox: https://codesandbox.io/s/serene-water-6h78k

Class-based or not, componentDidUpdate and useEffect seems to trigger a lot. See console of sandbox.

Swizec commented 5 years ago

Hey @jmcruzmanalo sorry I just noticed this. You are right that useDimensions can trigger a lot of updates.

One way to combat that is using the measurements in your useEffect 2nd prop so it only runs when they change. I've also just added a feature that lets you pass a liveMeasure flag into useDimensions when using the hook.

const MyComponent = () => {
    const [stepRef, stepSize] = useDimensions({ liveMeasure: false });

    // useDimensions never updates and won't trigger re-renders
    console.log("Step is at X: ", stepSize.x);

    return (
        <div>
            <div ref={stepRef}>This is a step</div>
        </div>
    );
};