Lesson
How React Hooks Components Capture Values (And How To Use the Latest Values Instead)
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.
- Duration
- 4 min
- Access
- Free
- Transcript
- Needs source
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:
- What value capturing means, and why it causes this bug
- How to use the "updater form" of the useState hook to update the array
- How to use the useRef hook to capture the values of the latest render in the callback