I have reviewed more than 1,000 front-end pull requests.
Like many junior developers, I made some common mistakes when I started,ย especially while using refs.
If you're in the same boat, here are 6 small mistakes you can quickly fix to use refs properly in React:
Mistake #1: Using a state when a ref would be a better choice
One common mistake is having a state when a ref would have been more suitable. Since ref updates don't trigger re-renders, they are perfect for situations where this behavior is unnecessary, resulting in better app performance.
Mistake #2: Using ref.current
vs. ref or using the ref value before it's set
When I first began, I often stumbled upon this mistake. I would use ref.current
before the value was actually passed, or I'd pass ref.current
to my functions instead of using ref directly. In the latter case, the ref object would change while I still held onto the value stored in ref.current
Mistake #3: Forgetting to use forwardRef
We probably all made this mistake. In fact, React doesn't let you pass a ref to a function component unless it's wrapped with forwardRef
. The fix? Simply wrap the component receiving the ref in forwardRef or use another name for your ref prop.
Mistake #4: Initializing the ref with an "expensive" function call
When you call a function to set the ref initial value, that function will be called with each render. If the function is expensive, this will unnecessarily affect your app performance. The solution? Memoize the function or initialize the ref during render (after checking that values are not set yet).
Mistake #5: Using a ref callback function that changes on every render
Ref callbacks can tidy up your code. However, be aware that React calls the ref callback whenever it changes. This means that when a component re-renders, the previous function is called with null as the argument, while the next function is called with the DOM node. This can lead to some unwanted flickering in the UI. The solution? Make sure to memoize the ref callback function.