29
loading...
This website collects cookies to deliver better user experience
Complete Tutorial on useRef is uploaded at Hubpages
useState()
declares the state variable while the the value is stored in the count variable. setCount
is the function used to update this value.//import useState from react
import React, { useState } from 'react';
function Count() {
// Declare a new state variable called count
const [count, setCount] = useState(0);
//import useRef hook
import React, { useRef } from "react"
export default function App() {
//create a variable to store the reference
const nameRef = useRef();
function handleSubmit(e) {
//prevent page from reloading on submit
e.preventDefault()
//output the name
console.log(nameRef.current.value)
}
return (
<div className="container">
<form onSubmit={handleSubmit}>
<div className="input_group">
<label>Name</label>
<input type="text" ref={nameRef}/>
</div>
<input type="submit"/>
</form>
</div>
)
}
Data or values stored in a reference or ref remains the same, even after component re-rendering, unlike states. So, References do not affect component rendering but states do.
useState returns 2 properties or an array. One is the value or state and the other is the function to update the state. In contrast, useRef returns only one value which is the actual data stored.
When the reference value is changed, it is updated without the need to refresh or re-render. However in useState, the component must render again to update the state or its value.
Complete Tutorial on useRef is uploaded at Hubpages