Welcome to our React JS tutorial! Today, we're diving deep into useRef, a powerful hook that gives us access to the DOM and enables us to work with mutable values in functional components.
useRef is a built-in hook in React that returns a mutable ref object. This object's .current property is initialized to the passed argument (if any) and can be updated using the ref.current = ... syntax.
useRef allows us to access the DOM element created by a React component.useRef, we can create a value that persists between renders, which can be useful for storing information that needs to survive updates.Let's start by creating a simple ref:
import React, { useRef } from 'react';
function MyComponent() {
const myRef = useRef(null);
// ...
}In the example above, myRef is a ref object that initially has a value of null.
Now, let's see how we can access the DOM element of a React component using useRef:
import React, { useRef, useState, useEffect } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const [text, setText] = useState('');
useEffect(() => {
console.log(inputRef.current.value); // prints the current input value
}, [inputRef]);
return (
<div>
<input type="text" ref={inputRef} value={text} onChange={e => setText(e.target.value)} />
<button onClick={() => inputRef.current.focus()}>Focus input</button>
</div>
);
}In the code above, we create a ref (inputRef) and use it to access the DOM input element. We also set up a state variable (text) to store the current input value. The useEffect hook is used to log the current input value whenever the inputRef changes.
Using useRef, we can create mutable values that persist between renders:
import React, { useRef, useState } from 'react';
function Counter() {
const countRef = useRef(0);
const [count, setCount] = useState(countRef.current);
const incrementCount = () => {
countRef.current += 1;
setCount(countRef.current);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment count</button>
</div>
);
}In the example above, we create a ref (countRef) and initialize it to 0. We then set up a state variable (count) that initially has the same value as the countRef. When the "Increment count" button is clicked, we increment the value of countRef and update the state accordingly.
What does `useRef` return in React?
That's it for today! We hope this tutorial has helped you understand how to use useRef for accessing the DOM and working with mutable values in React. Happy coding! š
š Note: Remember, useRef is an essential tool in your React toolkit, and mastering it will help you build more complex and interactive applications. Keep practicing, and soon you'll be able to create amazing projects using React! š