DEV Community

Cover image for Exploring the Power of useRef hook.✨
Abdullah Official
Abdullah Official

Posted on

Exploring the Power of useRef hook.✨

The useRef hook is a built-in React hook that is used to create a reference to a DOM node so that you can interact with it directly. The useRef hook is a function that accepts a maximum of one argument as the initial value and returns an object. The returned object has a special property called current.

Here’s an example of how you might use the useRef hook to create a simple form that takes input from the user:

import { useRef } from 'react';

function MyForm() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(inputRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={inputRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, we are using the useRef hook to create a reference to an input element in our form. We then pass this reference to the input element using the ref prop. This allows us to access the input element's value property in our handleSubmit function, which is triggered when the form is submitted.

We are also using the preventDefault() method to prevent the form from refreshing the page when the user submits it.

The example above is just a simple one, you can add more inputs and logic to it, also you can use useState to handle the form inputs and submit them to a server or any other logic that you want to apply.

We use the useRef hook to store the values without triggering the re-render of the component. We can't do this with the useState hook. Updating a state value with the useState hook causes the component to be re-rendered. If we want to keep our component in sync with the state, we use the useState hook. Sometimes we just don’t want the component re-render when the value is updated, there we useuseRef hook.

I hope that this article helped you understand what the useRef hook is and how to use it.

If you like such stories and want to support me, please share my content as much as you can. 👇 Your support is very important for me to write the next story — thank you.

Follow me on Twitter, LinkedIn

Top comments (0)