A mutable variable in React is a variable whose value can be changed during the lifetime of a component. Unlike a constant or a state variable, its value can be updated, which can be useful in certain scenarios like maintaining the value of a form input or an element’s position on the screen. The useRef hook can be used to create and maintain a mutable variable.
Prerequisites
Steps to create React Application:
Step 1: Create a React application using the following command:
npx create-react-app "foldername"
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Example 1: In this example, useRef is used to create a mutable variable with an initial value of 0. The increment function updates the value stored in mutableVariable.current by incrementing it by 1.
// App.js import React, { useRef } from 'react' ;
function App() {
const mutableVariable = useRef(0);
const increment = () => {
mutableVariable.current += 1;
};
return (
<div>
<p>{mutableVariable.current}</p>
<button onClick={increment}>Increment</button>
</div>
);
}; export default App;
|
Note that this code will not update the value of mutableVariable.current because React will not re-render the component after the button is clicked and the increment function is executed. The value of mutableVariable.current is only updated, but the component is not re-rendered to reflect the updated value.
If you want to see the value of mutableVariable after clicking on the Increment button you just need to add:
console.log(mutableVariable.current);
after mutableVariable.current += 1: in increment function.
Now you can see the value of mutableVariable after clicking on the Increment button.
Output:
Example 2: In this example, useRef is called and it returns a ref object with a current property. The ref prop is then passed to the input element, allowing us to access its value through inputRef.current.value.
// App.js import React, { useRef } from 'react' ;
function App() {
const inputRef = useRef( "" );
const handleSubmit = () => {
console.log(inputRef.current.value);
};
return (
<div>
<input type= "text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}; export default App;
|
Output:
Conclusion
The useRef hook is a useful tool for keeping a mutable value in React and can be used to improve the performance, code organization, and overall quality of your React applications.