Sunday, December 29, 2024
Google search engine
HomeLanguagesHow to keep a mutable variable in react useRef hook ?

How to keep a mutable variable in react useRef hook ?

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.

Mutable values can be useful in a variety of scenarios, such as storing the value of a form input that should persist even when the input changes, or maintaining the position of an element on the screen that should persist even when the component re-renders.

ref and useRef: The ref is a special prop in React that allows you to access the value of an element from the DOM. It provides a way to access the underlying DOM element, which is useful in cases where you need to access the value or state of an element directly, without having to manage it with state or props.

Syntax:

<input type="text" ref={inputRef} />

useReF is a hook in React that returns a mutable object with a current property. You can use useRef to store a value that you want to persist across renders of a component. The value stored in the useRef hook does not trigger a re-render of the component when it changes, making it useful for storing values such as the value of an input element, a timer, or a reference to a DOM element.

Syntax:

const inputRef = useRef(initialValue);

In combination, ref and useRef can be used to store a reference to a DOM element, and access its value, without triggering a re-render of the component. To use ref and useRef together, you simply pass a useRef hook as the ref prop to the element you want to access and then use the .current property of the useRef hook to access the value of the element.

Importing: To use useRef, you need to import useState from react as shown below:

import React, { useRef } from "react"

There are several benefits to using the useRef hook in React:

Persistent values: The value of a useRef hook remains unchanged even when the component re-renders. This makes it a useful way to store values that need to persist between renders, such as the value of an input element, a timer, or a reference to a DOM element.

No re-renders: Since the value of a useRef hook does not change when the component re-renders, it does not trigger a re-render of the component. This can improve the performance of your application, especially in large or complex components.

Easy to use: The useRef hook is very easy to use. Simply call the hook, and then use the .current property to access the value of the ref. No state management or complex data structures are required.

Better code organization: By using the useRef hook to store values that do not trigger re-renders, you can make your code easier to understand and maintain. The separation of mutable and immutable values can also make it easier to debug your code.

Creating 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

Javascript




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:

How to keep a mutable variable in react useRef hook?

How to keep a mutable variable in react useRef hook?

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

Javascript




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:

How to keep a mutable variable in react useRef hook?

How to keep a mutable variable in react useRef hook?

When the submit button is clicked, the handleSubmit function is called, which logs the value of the input to the console. Since the inputRef value does not change when the component re-renders, the input value is always up to date and does not trigger a re-render of the component.

In this way, useRef can be used to keep a mutable value in React, such as the value of an input element, a timer, or a reference to a DOM element, without triggering a re-render of the component.

In 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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments