Skip to content

What’s the best way to handle scroll with effects hooks? #16289

@dbismut

Description

@dbismut

Hi, this is not issue per se, more a question on what’s the best recommended way of handling scroll with hooks.

I want to freeze and unfreeze a div on demand (freezing hides the div overflow and scrolls it to the current body scroll, unfreezing scrolls the body back to its previous position and frees the overflow of the div). I believe this can be handy when dealing with transitions.

Essentially to freeze the div you would need to read the current window.scrollY, add the frozen class (which sets position: fixed and overflow: hidden) to the div and immediately scroll it to the scroll position you’ve just read.

I tried several implementations, using useEffect, useLayoutEffect, a mix of both or directly manipulating the DOM (ie adding the class manually declaratively).

https://codesandbox.io/s/freezing-dom-6k7lb

The first three implementations sometimes show a flash on Safari, only the last one is flash-free on both Safari desktop and mobile.

I’d be happy to get some thoughts on what’s the best strategy t prevent any flashes, ie adding the frozen class and scrolling the div in the same render cycle.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions