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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay