Using useRef(), useState(), useEffect

RMAG news

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)

useRef explanation

key differences

useState Use Cases

useRef Use Cases

Conclusion

Please follow and like us:
Pin Share