React useRef Hook

Eman Awad
Nov 20, 2023
1 min read
post_comment0 Comments
post_like0 Likes

useRefhook is a feature in React that allows you to create a mutable object called “ref” . This object can hold a reference to a DOM element or a mutable value in the functional component.

It is commonly used to interact with and manipulate the DOM directly. You can also useuseRefto hold mutable values that won't trigger a re-render when they change.

Here's a simple example of howuseRefworks to interact with and manipulate the DOM directly:

function MyComponent() { // Creating a 'myRef ' ref an assign 'null' as default value to it const myRef = useRef(null); useEffect(() => { // focus on input element when the component mounts myRef.current.focus(); }, []); // Attaching Ref to a input DOM Element: return ; }

In this example, themyRefref is linked to the input element via therefattribute.myRef.currentprovides direct access to this input in the DOM, enabling us to focus on it when the component mounts.

Here's a simple example of howuseRefworks to handle a mutable value:

function MyComponent() { // Creating a 'count' ref an assign '0' as default value to it const count = useRef(0); const incrementCount = () => { count.current += 1; }; return (

Count: {count.current}

); }

In this example, thecountref holds a mutable value (0 initially), and when the button is clicked, it increments the value without triggering a re-render.

📍References :

🔗React.dev