Mutable Current Property
When the current property of useRef is mutable, it means that the value of the property can be changed directly. React treats the current property as mutable, and any attempt to change the current property will trigger a re-render of the component. This is because when the current property is mutable, React assumes that the component may have a dependency on the value held in the useRef object, and therefore any changes to the object will affect the component’s rendering.
Example: Consider the same example of a counter that increments its value when the “Increment” button is clicked.
Javascript
import React, { useState, useRef } from "react" ; function App() { const [count, setCount] = useState(0); const countRef = useRef(count); const handleIncrement = () => { countRef.current += 1; setCount(countRef.current); console.log(countRef.current); }; return ( <div align= "center" > <h1 style={{ color: "green" , fontSize: "3rem" , fontWeight: "bold" , }} > w3wiki </h1> <p>Count: {count}</p> <button onClick={handleIncrement}>Increment</button> </div> ); } export default App; |
Step to Run Application: Open the terminal and type the following command.
npm start
Output:
Mutable and Immutable useRef Semantics with React JS
The useRef hook in React.js is essential for preserving references to DOM nodes or persistent values across renders. It accommodates both mutable and immutable values, influencing React’s re-rendering behavior based on whether changes are made to mutable or immutable properties of the useRef hook.
Table of Content
- Immutable Current Property
- Mutable Current Property