This content originally appeared on DEV Community and was authored by _Khojiakbar_
The Magical Mirror: Understanding useRef
Imagine you have a magical mirror. This mirror can remember a special spot in your room. Whenever you look into the mirror, it points to that exact spot, even if you move things around in your room.
In React, useRef
is like this magical mirror. It helps you keep track of a special spot (or reference) in your code.
The Story of Timmy and His Toy Box
Meet Timmy
Timmy loves playing with his toys. He has a magical toy box where he keeps all his toys. One day, Timmy decides he wants to remember where his favorite toy robot is, even if he adds more toys to the box or moves them around.
Timmy's Magical Marker: useRef
Timmy uses a magical marker (like useRef) to mark the spot where his toy robot is in the toy box. No matter how many toys he adds or how much he moves them, the magical marker always knows where the toy robot is.
How useRef
Works in Code
Let's see how Timmy's magical marker works in React:
Funny Sample with Timmy
The Robot Naming Game
Timmy wants to give his robot a name. He uses useRef to remember what he named it, even if he forgets!
import React, { useRef } from 'react';
function RobotNaming() {
const robotNameRef = useRef(null);
const nameRobot = () => {
alert(`The robot's name is: ${robotNameRef.current.value}`);
};
return (
<div>
<input type="text" ref={robotNameRef} placeholder="Name the Robot" />
<button onClick={nameRobot}>Name Robot</button>
</div>
);
}
export default RobotNaming;
Summary
Timmy's magical marker, the useRef hook, helps him keep track of his favorite toy robot's spot, even if things change in his toy box. Similarly, useRef
in React helps you keep track of references to DOM elements or other values without causing the component to re-render. It's like having a magical marker that always knows where your important stuff is!
This content originally appeared on DEV Community and was authored by _Khojiakbar_
_Khojiakbar_ | Sciencx (2024-08-07T16:35:59+00:00) useRef() in React . . .. Retrieved from https://www.scien.cx/2024/08/07/useref-in-react-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.