DEV Community

Cover image for useState vs useRef in react and when to use what with example
jeetvora331
jeetvora331

Posted on

useState vs useRef in react and when to use what with example

The differences between useState and useRef

Use useState when
-You need to manage local state within a component.
-You want the component to re-render when the state changes.
-You need to store primitive values like strings, numbers, or booleans.

Use useRef when
-You need to store a value that should persist across renders but not trigger a re-render when it changes.
-You need to access DOM elements directly.
-You need to store mutable objects.

Example

Let's consider a real-life example of a form with validation. In this scenario, we will use both useState and useRef to demonstrate their respective use-cases.

Image description

Image description

CODE:

import React, { useState, useRef } from "react";

export function App(props) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isValid, setIsValid] = useState(false);
  const emailInputRef = useRef();

  const validateForm = () => {
    setIsValid(email.includes("@") && password.length >= 8);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!isValid) {
      emailInputRef.current.focus();
    } else {
      // Submit Action
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        ref={emailInputRef}
        onChange={(e) => setEmail(e.target.value)}
        onBlur={validateForm}
        placeholder="Email"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        onBlur={validateForm}
        placeholder="Password"
      />
      <button type="submit">Sign Up</button>
      {!isValid && <p style={{"color": "red"}}>Please enter a valid email and password.</p>}
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, we use useState to manage the email, password, and validation state. We also use useRef to create a reference to the email input element, which allows us to focus on it if the form is not valid upon submission

Top comments (0)