Skip to main content

Command Palette

Search for a command to run...

useRef Hook?

Published
5 min readView as Markdown
useRef Hook?
T

I'm a recent graduate with a degree in Mechanical Engineering but I have a passion for web development. I have hands on in ReactJS and I have experience building responsive, user-friendly web applications using this framework. I gained hands-on experience in web development through several projects . I'm proficient in HTML, CSS, JavaScript, and I have experience working with various front-end technologies such as ReactJS, Redux, and Bootstrap. I'm also familiar with back-end development such as Node.js and Express.js.

In this article, we will learn about useRef Hook

What is useRef Hook?

The useRef hook returns a mutable ref object with a current property. This current property can be assigned any value and will persist across re-renders without causing the component to re-render.

It can be used to access a DOM element directly.

It can be used to store a mutable value that does not cause a re-render when updated.

It is often used for the following scenarios:

  1. Accessing DOM elements: You can use useRef to get a reference to a DOM element and perform operations on it, such as changing its styles or focusing it.

  2. Storing previous values: Since the current property of a ref does not cause re-renders, you can store and access the previous value of a state or prop to perform comparisons or calculations.

  3. Storing mutable values: useRef can be used to store any mutable value that needs to persist across renders, such as timers, event listeners, or other objects that should not trigger re-renders.

Here's an example that demonstrates the usage of useRef:

import React, { useRef } from 'react';

const ExampleComponent = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

In this example, useRef is used to create a ref called inputRef. The ref is then attached to the <input> element using the ref attribute. When the button is clicked, the handleClick function is called, and it uses the inputRef.current to access the underlying DOM element and call the focus() method, which focuses the input.

By using useRef, you can access and manipulate values or DOM elements without causing unnecessary re-renders in your components. It provides a way to retain references to values that persist across renders and perform operations on them as needed.

Lets take another example

import React, { useState, useEffect, useRef } from 'react';

const ExampleComponent = () => {
  const [count, setCount] = useState(0);
  const previousCountRef = useRef();

  useEffect(() => {
    previousCountRef.current = count;
  }, [count]);

  const handleIncrement = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Current Count: {count}</p>
      <p>Previous Count: {previousCountRef.current}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
};

In this example, we have a count state variable that keeps track of the current count value. We also create a ref called previousCountRef using useRef.

Inside the useEffect hook, we update the previousCountRef.current with the current value of count whenever it changes. This allows us to store and access the previous value of count between renders.

In the component's render, we display the current count and the previous count using count and previousCountRef.current respectively. Whenever the "Increment" button is clicked, the handleIncrement function is called, which updates the count state and triggers a re-render.

By using useRef to store the previous value of count, we can access it without causing a re-render. This is useful when you need to compare the current and previous values or perform calculations based on the previous value.

Another example

import React, { useRef } from 'react';

const ExampleComponent = () => {
  const countRef = useRef(0);

  const incrementCount = () => {
    countRef.current++;
    console.log('Current Count:', countRef.current);
  };

  return (
    <div>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
};

In this example, we have a button that triggers the incrementCount function when clicked. Inside the function, we access the current value of the countRef using countRef.current and increment it by one. We then log the current count to the console.

The key difference here is that the countRef.current value is mutable and can be directly modified. It allows us to maintain state-like behavior without triggering re-renders in React. The value stored in countRef.current persists across re-renders, but changes to it won't trigger a re-render.

By using useRef to store a mutable value, we can maintain and update the value without relying on component state. This can be useful for scenarios where you need to track and modify values without triggering re-renders or managing complex state updates.

Difference between useState and useRef

The main difference between both is :

useState causes re-render, useRef does not.

  1. useState: The useState hook is used to manage state in a functional component. When the state value managed by useState changes, it triggers a re-render of the component. This means that any component that uses useState will re-render when the state value is updated. React compares the previous state value with the new state value to determine if a re-render is necessary.

Example:

import React, { useState } from 'react';

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

In the above example, when the count state is updated using setCount, it triggers a re-render of the component to reflect the updated count value.

  1. useRef: The useRef hook is used to store mutable values that persist across re-renders. The value stored in a useRef does not trigger a re-render when it changes. Instead, it allows you to access and modify the value without causing a re-render. The component will not update or reflect changes in the useRef value.

Example:

import React, { useRef } from 'react';

const MyComponent = () => {
  const countRef = useRef(0);

  const increment = () => {
    countRef.current += 1;
    console.log('Count:', countRef.current);
  };

  return (
    <div>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

In the above example, the countRef holds the current count value, but updating it does not trigger a re-render of the component. The updated value is accessible through countRef.current, but the component's rendering does not reflect the updated value.

Overall, useState is used for managing state that triggers re-renders, while useRef is used for storing values that do not trigger re-renders and are typically used for accessing or persisting values across re-renders.

More from this blog

J

JSpoint

53 posts

Discover the power of JavaScript with our comprehensive website. Explore resources and practical examples to enhance your coding skills. From frontend development to backend scripting.