#typescript#reactjs#beginers
Hi guys!
In this post we will be learning what the useRef and useState hooks are, their differences and when to use which.
The code examples in this post will involve only functional components, however most of the differences and uses cover both class and functional components.
useState is a built in react hook that allows you to store information as states in a variable. It lets you add React states to functional components.
In the example below, 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);
/* code other here */
}
See a more detailed example of useState() here.
The useRef hook is a built-in React hook that takes one argument or parameter as its initial value and returns a reference or persisted mutable values. This reference, or ref for short, contains the value which can be retrieved using the current property.
We can also store user inputs in refs and display the collected data like this:
//import useRef hook
import React, { useRef } from "react"
export default function App() {
//create a variable to store the reference
const nameRef = useRef();
const handleSubmit = (e) => {
//prevent page from reloading on submit
e.preventDefault()
//output the nameconsole.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>
)
}
Refs are useful when getting user input, DOM element properties and storing constantly updating values.
However if you are storing component related info or use methods in components states are the best option.
So in conclusion, both the hooks have their fair bit of pros and cons, and they will be utilised according to the situation and use.
Thanks for reading!
* Note: There probably is much more that could have been mentioned here but in short, these were the most important differences.