DEV Community

Serge Jabo Byusa
Serge Jabo Byusa

Posted on

4 2

Working with Ref in React

When you need to only read a value but no need to change it just use Refs (better than State in this case)
But in general rarely use Refs, just use useState


Step 1
import useRef from react

import React, {useRef } from 'react';
Enter fullscreen mode Exit fullscreen mode

Step 2

inside the method, set the values of refs

const enteredUsername1 = nameInputRef.current.value;
const enteredUserAge1 = ageInputRef.current.value; 
Enter fullscreen mode Exit fullscreen mode

Step 3
use the ref

 ref={nameInputRef}
Enter fullscreen mode Exit fullscreen mode

Example of full code

import React, {useRef } from 'react';

import Card from '../UI/Card';
import classes from './AddUser.module.css';

const AddUser = (props) => {
  const nameInputRef = useRef();
  const ageInputRef = useRef();

  const addUserHandler = (event) => {
    event.preventDefault();

    const enteredUsername1 = nameInputRef.current.value;
    const enteredUserAge1 = ageInputRef.current.value; 

    props.onAddUser(enteredUsername1, enteredUserAge1);

   //in case you want to set your ref to null
    nameInputRef.current.value = ''
    ageInputRef.current.value = ''
  };


  return (
    <div>
      <Card className={classes.input}>
        <form onSubmit={addUserHandler}>
          <label htmlFor="username">Username</label>
          <input
            id="username"
            type="text"
            ref={nameInputRef}
          />
          <label htmlFor="age">Age (Years)</label>
          <input
            id="age"
            type="number"
            ref={ageInputRef}
          />
          <button type="submit">Add User</button>
        </form>
      </Card>
      </div>
  );
};

export default AddUser;

Enter fullscreen mode Exit fullscreen mode

NB: Using Ref makes the inputs to be uncontrolled components (value in them is not controlled by react)

👋 Kindness is contagious

Please leave your appreciation by commenting on this post!

It takes one minute and is worth it for your career.

Get started

Thank you!

Top comments (0)

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

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay