Mixing imperative and reactive updates

(Alex Guerra) #1

Imagine a component in the vein of react-virtualized where the elements returned from render are dependent on two things: props and the current scroll position. The component listens to scroll position via an onScroll handler and saves in state so that it may use it when deciding what to display in render.

Now imagine you need to provide a way to scroll to a particular element. Also imagine that scrolling to a particular element will almost always coincide with a change to props.

What’s the best way to write this?

The issue I’m having is in scheduling. An imperative interface like scrollToElement(index) needs to be provided because, well, the scroll is triggered imperatively via an event. The actual scrolling (via setting scrollTop on the windowed dom node) needs to happen in componentDidUpdate, since the index-to-be-scrolled-to may not exist until after the next render. However the scrollTop value used in that render should be the scrollTop-to-be so that we’re not rendering one thing, setting scrollTop, and then immediately rendering again.

I’ve run into this imperative/declarative impedance mismatch before and I’ve struggled to condense it down to a simple statement, but I’m hoping a discussion could be enlightening!