Unfortunately, useRef is underrated. It is not among the most popular hooks, but it is beneficial. Knowing how and where to use it can achieve great results.
useRef is a React Hook that lets you reference a value not needed for rendering.
React will remember the value you create through useRef, whether you are making a JavaScript object referencing a node in the DOM or a simple value, and it will not be lost during re-renders.
Accessing DOM Elements:
Storing Mutable Values:
Here are some examples to illustrate the power of useRef.
import React, { useRef } from 'react'; const Counter = () => { const refCount = useRef(0); const refInputField = useRef(null); const onClick = () => { refCount.current = refCount.current 1; refInputField.current.focus(); } return ( > ); }; export default Counter;
In this example:
Another common use case for useRef is keeping track of previous values.
import React, { useRef, useEffect, useState } from 'react'; const PreviousValue = () => { const [count, setCount] = useState(0); const prevCountRef = useRef(); useEffect(() => { prevCountRef.current = count; }, [count]); return (); }; export default PreviousValue;Current Count: {count}
Previous Count: {prevCountRef.current}
In this example:
useRef can be used to persist values across renders without causing a re-render, unlike useState. This is particularly useful for storing values that don't directly impact the UI but need to be remembered.
Example: Tracking the render count of a component.
import React, { useRef, useEffect } from 'react'; const RenderCounter = () => { const renderCount = useRef(0); useEffect(() => { renderCount.current = 1; }); return (); }; export default RenderCounter;This component has rendered {renderCount.current} times
useRef is invaluable when working with third-party libraries that require direct manipulation of DOM elements, such as integrating with charting libraries, managing video players, or handling animations.
Example: Integrating a chart library.
import React, { useRef, useEffect } from 'react'; import Chart from 'chart.js/auto'; const ChartComponent = () => { const chartRef = useRef(null); useEffect(() => { const ctx = chartRef.current.getContext('2d'); new Chart(ctx, { type: 'line', data: { labels: ['January', 'February', 'March', 'April'], datasets: [{ label: 'Sales', data: [65, 59, 80, 81], }], }, }); }, []); return ; }; export default ChartComponent;
In complex applications where performance is critical, using useRef to store mutable objects can help avoid unnecessary re-renders.
Example: Storing a mutable state object.
import React, { useRef } from 'react'; const MutableState = () => { const state = useRef({ name: 'John Doe', age: 30, }); const updateName = (newName) => { state.current.name = newName; console.log('Name updated:', state.current.name); }; return (); }; export default MutableState;
Using useRef can help avoid closure issues by providing a stable reference to a value that persists across renders.
Example: Timer with useRef to avoid stale state.
import React, { useRef, useState, useEffect } from 'react'; const Timer = () => { const [count, setCount] = useState(0); const countRef = useRef(count); countRef.current = count; useEffect(() => { const intervalId = setInterval(() => { setCount(countRef.current 1); }, 1000); return () => clearInterval(intervalId); }, []); returnCount: {count}; }; export default Timer;
Hooks are great, and you should use them. You can achieve a lot if you understand how React works and apply hooks correctly. useRef is particularly powerful for:
By understanding and utilizing useRef, you can write more efficient and effective React components. The true power of hooks lies in understanding their behavior and applying them judiciously.
Do you know, useState is not always the correct answer?
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3