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 useRef
hook, 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 π€
View my portfolio app
Also, do follow me on Twitter <3
Top comments (2)
very cool when you only need the values of the fields when submitting