Understanding useRef in React

React is an incredibly powerful and flexible JavaScript library for building user interfaces. One of its most useful yet sometimes perplexing concepts are hooks, introduced in version 16.8. Among these hooks, useRef is particularly intriguing due to its versatility.ntre estos hooks, useRef es particularmente interesante debido a su versatilidad.

What is useRef?

The useRef hook is a function that allows React components to access and interact with DOM nodes or store any mutable value that doesn’t cause a re-render when updated.

const miRef = useRef(valorInicial);

The object returned by useRef has a .current property that is initialized with the passed argument (initialValue). This object will persist for the entire lifetime of the component.

Common Uses of useRef

Accessing the DOM

One of the most common uses of useRef is to access a DOM element directly. This is useful when you need to manipulate an element without causing a re-render.

function MyComponent() {
const myInput = useRef(null);

const focusInput = () => {
myInput.current.focus();
};

return (
<>



);
}

Storing Values

useRef is also handy for keeping a value that you don’t want to cause re-renders when it changes, such as the previous state of a component or an interval counter.

function TimerComponent() {
    const intervalRef = useRef();

    useEffect(() => {
        const id = setInterval(() => {
            // tu lógica de intervalo aquí
        }, 1000);
        intervalRef.current = id;
        return () => clearInterval(intervalRef.current);
    }, []);

// ...
}

Why Not Just Use useState?

You might wonder why not just use useState to store values. The key difference is that changing the value of .current in the object returned by useRef will not trigger a re-render, whereas changing state with useState will.

Conclusion

useRef is an essential tool in the React toolkit. Whether you need to interact with the DOM or maintain values between renders without causing unnecessary updates, useRef is your go-to. With its help, you can write more efficient components and perform tasks that would otherwise be complicated in React’s reactive paradigm.