##### You know all the react basics, and you would like to get more advanced aka in-depth knowledge? great, let's rock
Advanced hooks
useRef
useRef
is a React Hook that lets you reference a value that’s not needed for rendering.
Refs can be used for a variety of purposes. One particular use for them is if you need to interact with the actual DOM (as opposed to the React virtualization of it) directly.
- Usage
- Referencing a value with a ref
- Manipulating the DOM with a ref
- Avoiding recreating the ref contents
This is pretty rare and really only when you need to derive measurements from the DOM (like width) or you’re using an external library and it needs a real DOM node to interact with.
useRef
returns a ref object with a single current
property initially set to the initial value you provided.
- Parameters
- initialValue: The value you want the ref object’s current property to be initially. It can be a value of any type. This argument is ignored after the initial render.
- Returns
- useRef returns an object with a single property:
- current: Initially, it’s set to the initialValue you have passed. You can later set it to something else. If you pass the ref object to React as a ref attribute to a JSX node, React will set its current property.
Changing the ref value
Changing a ref does not trigger a re-render. This means refs are perfect for storing information that doesn’t affect the visual output of your component. For example, if you need to store an interval ID and retrieve it later, you can put it in a ref. To update the value inside the ref, you need to manually change its current
property:
Later, you can read that interval ID from the ref so that you can call clear that interval:
- ➡️ By using a ref, you ensure that:
- ➡️ You can store information between re-renders (unlike regular variables, which reset on every render).
- ➡️ Changing it does not trigger a re-render (unlike state variables, which trigger a re-render).
- ➡️ The information is local to each copy of your component (unlike the variables outside, which are shared).