useState() vs. useRef(): Understand the Technical

React is a popular JavaScript library that allows developers to create reusable and modular user interfaces. useState() and useRef() are two of the most commonly used hooks in React, but they serve different purposes.

In this article, we will discuss the differences between useState() and useRef() and when to use each of them.

What Is useState()?

useState() is a built-in React hook that allows you to add a state to functional components. It takes an initial value as an argument and returns an array with two elements: the current state and a function to update that state.

Here’s an example of how to use useState() to add a counter to a functional component:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

In this example, we use the useState() hook to define a count variable with an initial value of 0. We also define a handleClick() function that updates the count state by calling the setCount() function.

When the user clicks the button, the handleClick() function is called, which updates the count state and triggers a re-render of the component.

What Is useRef()?

useRef() is another built-in React hook that allows you to store a mutable value that persists between renders. Unlike useState(), useRef() does not trigger a re-render when its value changes.

Here’s an example of how to use useRef() to get the value of an input field:

import React, { useRef } from 'react';

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

  function handleSubmit(event) {
    event.preventDefault();
    console.log(inputRef.current.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, we use the useRef() hook to create a reference to the input element. When the user submits the form, the handleSubmit() function is called, which logs the current value of the input element to the console. 

Differences Between useState() And useRef()

The main difference between useState() and useRef() is that useState() is used to manage a state that triggers a re-render when it changes while useRef() is used to store mutable values that do not trigger a re-render.

Here are some key differences between the two hooks:

useState() Triggers a Re-Render When Its Value Changes, While useRef() Does Not

As we saw in the examples above when you update the state using useState(), React automatically re-renders the component to reflect the new value. However, when you update the value stored in a useRef() reference, React does not re-render the component.

useState() Is Used to Manage State, While useRef() Is Used to Store Mutable Values

useState() is primarily used to manage state in a React component. You can use it to store and update values that affect the component’s appearance and behavior.

On the other hand, useRef() is used to store mutable values that do not affect the component’s appearance or behavior directly. You can use it to store references to DOM elements or to store values that need to persist between renders but do not affect the component’s state.

The Value Returned by useState() Is Always a State Value, While useRef() Can Return Any Mutable Value

When you use useState(), the value returned by the hook is always a state value, meaning it is intended to be used to manage and update the state within the component.

In contrast, useRef() can be used to store any mutable value, not just state values. For example, you can use useRef() to store a reference to a DOM element or to store a mutable value that needs to persist between renders but does not directly affect the component’s state.

Here’s an example of how you can use useRef() to store a reference to a DOM element:

This text can be changed

);
}” data-lang=””>

import React, { useRef } from 'react';

function MyComponent() {
  const myRef = useRef(null);

  function handleClick() {
    myRef.current.style.color="red";
  }

  return (
    <div>
      <p ref={myRef}>This text can be changed</p>
      <button onClick={handleClick}>Change text color</button>
    </div>
  );
}

In this example, we use useRef() to create a reference to the p element. When the user clicks the button, the handleClick() function is called, which updates the color of the text by accessing the current property of the myRef object.

Notice that in this example, we are not using myRef to manage the state within the component. Instead, we are using it to store a mutable value (the reference to the p element) that we can access and modify outside of the component’s state.

In conclusion, both useState() and useRef() are important hooks in React that serve different purposes. useState() is used to manage the state in a component and trigger re-renders when the state value changes, while useRef() is used to create a mutable reference to a value that does not trigger re-renders.

useState() is useful for managing component state that changes over time, such as user input or component visibility, while useRef() is useful for storing a reference to a DOM node or a value that needs to persist across renders.

It’s important to note that useState() should be used when you need to update the state of a component and trigger re-renders while useRef() should be used when you need to store a mutable reference to a value that does not cause re-renders. Understanding the differences and use cases of these hooks can help you write more efficient and effective React components.


Source link