Day 04: Referencing Values with Refs

Moazam AliMoazam Ali
2 min read

#100DaysOfCode

Day 04: Referencing Values with Refs

Learned about refs, which is used when we want a component to remember something but you don’t want that information to trigger new renders, that’s where you use the useRef hook from React.

If you create a variable with it, it’ll remember its value but would not trigger new renders. useRef returns an object with a current value. The ref.current property is mutable, which means it is read and writes both. This is what makes it an “Escape hatch”

Setting state re-renders a component. Changing a ref does not!

When a piece of information is used for rendering, keep it in state. When a piece of information is only needed by event handlers and changing it doesn’t require a re-render, using a ref may be more efficient.

Don’t read or write your ref during rendering otherwise, it will be hard to predict.

When to use Refs? Typically it’ll be used with external APIs, often browser APIs that would not affect the appearance of the component.

Source article

https://react.dev/learn/referencing-values-with-refs

In order to manipulate the DOM with Refs, you have to create a Ref with useRef hook and pass the null value as an initial value. Pass this Ref into the ref prop of the DOM element you want to reference.

Example

<input ref={inputRef}>

And now you can call any browser API on this ref from event handlers.

#reactjs #frontenddev #webdev #javascript #learnreact

0
Subscribe to my newsletter

Read articles from Moazam Ali directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Moazam Ali
Moazam Ali

Frontend Developer who is always passionate in discovering new stuff and building networks.