DEV Community

masonbarnes645
masonbarnes645

Posted on • Updated on

Using useRef(), useState()

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

Before getting into useState() and useRef(), it's important to understand the React render cycle. When a state in a React component changes, the component re-renders to reflect this change in the UI. This re-rendering is a crucial aspect of React’s declarative approach, ensuring that the UI is always in sync with the current state of the application. However, not all changes require a re-render, which is where useRef comes in handy.

Image description

useState explanation

useState() is a commonly used hook in React, and is necessary in adding functionality to many different features. 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'
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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. It is important to note that if you want to update the state correctly, you need to use the set function. You cannot modify the variable directly. State is also immutable, meaning in cannot be changed. This may seem impossible considering how we use state, but within the context of one render, state is immutable. It can only change in between renderings. 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);

}

Enter fullscreen mode Exit fullscreen mode

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

An example of a frequent use for useState() would be handling a light/dark
mode for a webpage

const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = () => setDarkMode(!darkMode);

Enter fullscreen mode Exit fullscreen mode

In this example, we can dynamically render the page based on the state "darkMode".

Another use of useState() is the handling of forms. We can use state to hand user input dynamically, updating state when the user types something.

const [name, setName] = useState('');
const handleInputChange = (e) => setName(e.target.value);

Enter fullscreen mode Exit fullscreen mode

As you can see, we change the value of the 'name' state whenever the user inputs something into the form.

useRef Use Cases

useRef() is useful when we need to change values without re-rendering the component. In this example use case, we want to store a mutable value. We can increment the value without re-rendering the component

const countRef = useRef(0);
const incrementRef = () => countRef.current++;

Enter fullscreen mode Exit fullscreen mode

It is also used in dynamic UI updates. useRef plays an important role in updating the UI dynamically. Storing reference to DOM elements or other mutable values allows components to update parts of the UI based on changing data or user inputs, without causing re renders.

Another valuable use of useRef is synchronizing with external libraries. By using a reference you assure that the UI is always using the most recent value it can display.

Overall, useRef is a valuable tool that maintains the freshest data, optimizing performance and enabling flexible updates in React applications.

Conclusion

useState() and useRef() are powerful tools in React with unique purposes. useState is essential for managing state that impacts rendering, while useRef is for persisting values across renders without causing a re-render. Understanding how to use these hooks, and when to use them, will allow you to create dynamic webpages

Top comments (0)