Hello again friends! In this article, I'm going to be explaining all you need to know about the useRef hooks. But before I go on, let me give a brief insight of what react hooks are.
React Hooks are simple JavaScript functions that we can use to isolate the reusable part from a functional component. Hooks can be stateful and can manage side-effects. React provides a bunch of standard in-built hooks: useState : To manage states. Returns a stateful value and an updater function to update it.
Alright now let's dive into the main topic, the useRef(initialValue) is a built-in React hook that accepts one argument as the starting value and returns a reference (aka ref). A reference is an object having a special property current .
import { useRef } from 'react';
function MyComponent() {
const startingValue = 0;
const reference = useRef(startingValue);
const someHandler = () => {
// Access reference value:
const value = reference.current;
// Update reference value:
reference.current = newValue;
};
// ...
}
reference.current accesses the reference value, and reference.current = newValue updates the reference value. Pretty easy right?
The two things to remember about references:
1.The value of the reference is persisted (remains unchanged) between component re-renderings;
2.Updating a reference doesn't trigger a component re-rendering.
Now, let's see how to use useRef() in practice.
import { useRef } from 'react';
function LogButtonClicks() {
const countRef = useRef(0);
const handle = () => {
countRef.current++;
console.log(`Clicked ${countRef.current} times`);
};
console.log('I rendered!');
return(
<>
<input type="text" ref = {countRef}/>
<button onClick={handle}>Click me</button>
</>
);
}
Using const countRef = useRef(0), a reference with the initial value of 0 is created.
At the point when the button is clicked, handle callback is summoned and the reference esteem is augmented: countRef.current++. After that, the console is logged with the reference value.
Refreshing the reference esteem countRef.current++ doesn't set off part re-delivering. "I rendered!" shows that this is the case. is logged to the console only once during initial rendering, and when the reference is updated, there is no re-rendering.
I hope this short explanation helps, thank you for reading
Top comments (0)