12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
15 : 06 : 00 : 19
Join egghead, unlock knowledge.

Want more egghead? It's 58% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 40% Off
Become a member
to unlock all features

    Capture values using the lifecycle hook getSnapshotBeforeUpdate in React 16.3

    Nik GrafNik Graf

    getSnapshotBeforeUpdate is a lifecycle hook that was introduced with React 16.3. It is invoked right before the most recently rendered output is committed and the value returned by it will be passed as a third parameter to componentDidUpdate. It enables your component to capture current values for example a scroll position before they are potentially changed.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: In this lesson, we are rendering the messages of a chat application. We can scroll up to see previous messages through the use of our chat component. The most recent messages are at the bottom, and therefore the component is scrolling through the bottom of list when componentDidMount is invoked.

    To add a new message, we can use the add button. While this is a good experience in case the user actively scrolled up, this is not comfortable in an active chat, where the user wants to read incoming messages.

    In order to get that experience, we need to capture the scroll position before render happens. Therefore, we can use getSnapshot before update, which receives prevProps and prevState. In our case, we alias the wrapper ref to wrapper for convenience.

    Then we return the result of a comparison, checking if the current scrolling position is at the end. The returned result is available in componentDidUpdate as a third parameter. In case the scroll position was at the end, we make sure it's again at the end. In case it wasn't, we don't do anything.

    If we add more different messages, the component always will scroll to the bottom. If we scroll up a bit further, then add one or more to our messages, the scroll position doesn't change. Now we have exactly the experience we are looking for.

    How does it work? getSnapshotBeforeUpdate is invoked right before the most recently rendered output is committed to the DOM. It enables your component to capture current values, for example, a scroll position before they potentially changed. In componentDidUpdate, which runs after the rendered output is committed to the DOM, we can leverage the snapshot information.