1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    How React Hooks Components Capture Values (And How To Use the Latest Values Instead)

    Brett CassetteBrett Cassette
    reactReact

    When you first start with React Hooks, you'll likely encounter some head-scratching bugs because function components capture the values they're rendered with.

    In this lesson, we see an example of such a bug by creating custom hook that wraps a WebSocket and exposes its messages array. We expect the array to contain all the messages, but it just contains the latest one.

    The lesson will teach you:

    1) What value capturing means, and why it causes this bug 2) How to use the "updater form" of the useState hook to update the array 3) How to use the useRef hook to capture the values of the latest render in the callback

    Code

    Code

    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
    Discuss

    Discuss