Home  >  Q&A  >  body text

When rendering happens inside onsubmit handler

I am new to react and while learning, I tried some code to understand controlled and uncontrolled components, I used usestate and useref. First time I gave the data name as: john and age:40 and clicked submit I saw name as "prakash" and age as 40 because I changed status during submit then I changed only age to 60 and click submit, it doesn't change the age, which I'm wondering because I changed the state during submit, which means it needs to render and change the age to 60. Can you explain why it doesn't change the age?

import { Fragment, useReducer, useRef, useState } from "react"



export default function Sample()
{
    
    const [name,setname]=useState();
    const age=useRef();
    const handelsubmit=(e)=>{
        e.preventDefault();
        setname("prakash")
        console.log(`${name},${age.current.value}`)
    }
    return(
    <form onSubmit={handelsubmit}>
        <label>name:{name}</label>
        <input type="text" onChange={(e)=>setname(e.target.value)} />
        <label>age:{age.current?.value==undefined?null:age.current.value}</label>
        <input type="text" ref={age}/>
        <button>submit</button>
    </form>
    )
}

P粉709644700P粉709644700212 days ago343

reply all(1)I'll reply

  • P粉819937486

    P粉8199374862024-02-22 09:48:10

    The reason changing the age input value does not update the displayed age value is that you are using the useRef hook to access the value of the age input field, which does not trigger a re-render when its value changes.

    In your code you will update the name status but not the age status when the form is submitted. When you access the age value using age.current.value, you are directly accessing the current value of the age input field without using the component's state. Since the value of age.current.value is not part of the component state, changing it will not trigger a rerender.

    After setting the status of name, you can update the status of age in the handelsubmit function:

    const [name, setName] = useState("");
    const [age, setAge] = useState("");
    const ageRef = useRef();
    
    const handleSubmit = (e) => {
      e.preventDefault();
      setName("prakash");
      setAge(ageRef.current.value);
    };
    
    return (
      
    setName(e.target.value)} />
    );

    reply
    0
  • Cancelreply