ahmed.zubaca
ahmed.zubaca

Reputation: 137

May I update state using useRef hook instead of onChange event in React js?

While looking for the way to avoid rendering of a component after each change in input field I came across a suggestion to use useRef instead of onChange event for state update. It seems ok in simple components, but since I am a beginner I do not know is this a good approach in more complex applications. Shell I continue this way or I should stick back to onChange event? I searched a lot to resolve this dilemma but was not able to find explicit answer. Any suggestion in this regard will be more tan welcomed.

This is how it looks in a component:

import React, { useRef, useState } from 'react';
import axios from 'axios';

const AddData : React.FC= () => {

  const initialData = {
    firstValue: '',
    secondValue : ''            
  }
  
  const [data, setData] = useState(initialData);
  const formRef = useRef<HTMLFormElement>(null);  
  const firstInputRef = useRef<HTMLInputElement>(null);
  const secondInputRef = useRef<HTMLInputElement>(null);          

  const handleSetData = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {    
    if(firstInputRef.current !== null && secondInputRef.current !== null) {      
      setData({
        ...data, 
            firstValue: firstInputRef.current.value,
            secondValue: secondInputRef.current.value                           
      })      
    }    
  }

  const handleFormSubmit = async (e:React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();   
    const {firstValue, secondValue} = data;
    if(firstValue !== '' && secondValue !== '') {         
      await axios.post('url', {
        ...data    
      }).then((response) => {  });      
    }
  }   

  return(
    <>      
      <form ref={formRef} onSubmit={handleFormSubmit}>        
        <input type='text' ref={firstInputRef} />
        <input type='text' ref={secondInputRef} />            
        <button onClick={handleSetData}> Submit Form </button>
      </form >
    </>
  );
}
export default AddData;

Upvotes: 2

Views: 8029

Answers (2)

NsdHSO
NsdHSO

Reputation: 153

You can use

const firstInputRef = useRef (null);

instead

 const firstInputRef = useRef <HTMLFormElement> (null);

Recommended by the react team useRef is recomandary use when you reading value, recomandary by team React. useRef will give you the same ref object on every render ,

Keep in mind that useRef doesn't notify you when its content changes, you want to use a function useCallback

Upvotes: 0

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

The approach you use are called uncontrolled form elements, and are alternative to controlled elements on official docs. In most cases React recommends to use controlled ones, but I suppose it is no harm to use the uncontrolled ones too if you wish.

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

Upvotes: 2

Related Questions