Difference between useState and useRef in terms of managing state?

image


useState

- useState() react hook which is used to update the state in the functional component.

- State generally refers to data or properties that need to be tracked in an application.

- useState accepts an initial state and returns two values: The current state and the past state.



useRef

- useRef () is a hook which provides a way to access the DOM. It returns a mutable ref object so you can access the value using .current property.

- Allows to persist values between renders.

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

useRef() example:

import { useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const inputElement = useRef();

  const focusInput = () => {
    inputElement.current.focus();
    console.log('Render happended')
  };

  return (
    <>
      <input type="text" ref={inputElement} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

/*
By clicking the button,
the input field focus.

Open the console log to checkrenderingnderi
*/



useState vs useRef

Take a look at the Sandbox below (use the full-screen button to view)



A combination of useState, useEffect, and useRef

The code below is the combination of useStateuseEffect, and useRef to keep track of the previous state.

In the useEffect, it updating the useRef current value each time the inputValue is updated by entering text into the input field:

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");

  useEffect(() => {
    previousInputValue.current = inputValue;
  }, [inputValue]);

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);