Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 27, 2022 02:38 am GMT

Using UseRef hook for form data

In this blog we will see how to use useRef hook instead of the useState hook.

The usual way:

export default function Form() {  const [email, setEmail] = React.useState("");  const [password, setPassword] = React.useState("");  const submit = (e) => {    e.preventDefault();    console.log(email, password);  };  // rerenders component eveytime when a character is added in the input field  React.useEffect(() => {    console.log("value changed");  }, [email, password]);  return (    <form onSubmit={submit}>      <label htmlFor="email">Email</label>      <input        type="email"        name="email"        value={email}        onChange={(e) => setEmail(e.target.value)}      />      <label htmlFor="password">Password</label>      <input        type="password"        name="password"        value={password}        onChange={(e) => setPassword(e.target.value)}      />      <button type="submit">Submit</button>    </form>  );}

Using useRef hook

export default function Ref() {  const emailRef = React.useRef(null);  const passwordRef = React.useRef(null);  const submit = (e) => {    e.preventDefault();    console.log(emailRef.current.value, passwordRef.current.value);  };  return (    <form onSubmit={submit}>      <label htmlFor="email">Email</label>      <input ref={emailRef} type="email" name="email" />      <label htmlFor="password">Password</label>      <input ref={passwordRef} type="password" name="password" />      <button type="submit">Submit</button>    </form>  );}

When we use useRefhook, the component does not rerender when the value of the input field changes. This is because the useRef hook does not cause any rerenders. It is used to store the reference of the DOM element.

Conclusion

In this blog we saw how to use useRef hook instead of useState hook. This is useful when we want to store the value of the input field without causing any rerenders

So that's it for this blog.
Hope you liked it
Also, do follow me on Twitter <3


Original Link: https://dev.to/kaartikn/using-useref-hook-for-form-data-2el5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To