This content originally appeared on DEV Community and was authored by masonbarnes645
Intro
Two very important hooks in React are useState() and useRef(). While used in similar ways, they have unique use cases in which each one is better equipped to solve a problem. In this post, I’ll go over useState and useRef, and go over some common use cases for each.
Render Cycle explanation
useState explanation
useState() is a commonly used hook in React, and is necessary in adding functionality to many different feature. useState() allows you to add a state variable to your component. Before we go over some of the uses for useState() lets look at how to implement it in your code. The first thing we need to do is import useState().
import { useState } from 'react'
Now that useState() is imported, we can call useState at the top level of our component to declare a state variable. Using array destructuring, we declare both a state variable, as well as a set function.
const [number, setNumber] = useState(0)
In this example, number is our state variable, and setNumber is our set function. That means we can use setNumber to update the state of number, and trigger a re-render of our componenet( this is important ). You may have also noticed a 0 after useState. That is the initial value, meaning that will be the value of the number state initially. That is a basic rundown of useState() and its functionality, useRef() is similar, but different in a very important way.
useRef explanation
useRef() is declared in a similar way to useState(), it accepts an initial value that you can change depending on what you need for your program.
import { useRef } from 'react'
function myComponent(){
const reference = useRef(null);
Unlike useState(), useRef() does not trigger a re-render. This makes useRef() ideal for keeping ‘references’ to values that do not need a re-render when they are changed.
useState Use Cases
useRef Use Cases
Conclusion
This content originally appeared on DEV Community and was authored by masonbarnes645