How to use useState and useRef together in React

Steps:

a) Import useRef and useState from React

b) Create input field and a button

c) Create a function on onClick event

d) Call useRef variable in useState function inside onclick event function

e) Give the ref in input field

f) Run your application

Import useRef and useState:

import { useState, useRef } from 'react';

Create input field and a button:

  return <>
  <h3>Hi, {enterUsername ?? ''}</h3>
  <input ref ={userName} type="text"/>
  <button onClick={handleClick}>Click for username</button>
  </>

Create a function on onClick event

    function handleClick()
  {
    setUsername(userName.current.value);
    // userName.current.value = '';  //uncomment if you want to clear the textbox value
  }

<button onClick={handleClick}>Click for username</button>

Call useRef variable in useState function inside onclick event function

  const userName = useRef();
  const [enterUsername, setUsername] = useState('');

  function handleClick()
  {
    setUsername(userName.current.value);
    // userName.current.value = '';
  }

Give the ref in input field

 const userName = useRef(); 
 <input ref ={userName} type="text"/>

Complete Code:

// useRef with usestate
import { useState, useRef } from 'react';

const App = () => {

  const userName = useRef();
  const [enterUsername, setUsername] = useState('');

  function handleClick()
  {
    setUsername(userName.current.value);
    // userName.current.value = '';  //uncomment if you want to clear the textbox value
  }
  return <>
  <h3>Hi, {enterUsername ?? ''}</h3>
  <input ref ={userName} type="text"/>
  <button onClick={handleClick}>Click for username</button>
  </>
}

export default App;

Output:

useref blogshub

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *