DEV Community

Cover image for A Brief Overview of useState
acw0415
acw0415

Posted on

A Brief Overview of useState

What is useState()?

So useState() creates a javascript object which you can use to dynamically update your web page asynchronously (not relying on information from elsewhere). It is similar to props with one key difference: state is handled within the component it is passed to.

How is it used?

When implementing state in your function it must first be imported from the react library.

import {useState} from "react"

Once it has been imported you can then use it by declaring it. The first item it returns will be the variable you are trying to set the state for, and the second item it returns will be a function for setting the value of that variable whatever it may be. Typically the naming convention for this function is the variable name you set preceded by the word "set" this helps to avoid confusion.

const [variable, setVariable] = useState()

Now, whatever is inside of the parentheses of useState will be the default value until it is "set" with the setter function that you named. You can make this an empty version of whatever value you expect your variable to be (i.e. [], {}, "") whether it's an array, an object, or a string.

When should I use it?

React utilizes state fairly heavily, due to the fact that it is so versatile, you will probably find yourself using it a lot. However when is it appropriate to use props instead? You may be asking. Well basically you should use state until the complexity increases (i.e. passing props down to child components) to the point where props seem to be required.

This is a brief, high level, overview of state as a concept. For more detail on how state actually works, and what it can be used for I would recommend you refer to react's documentation:

I hope this helps a bit with understanding the concept!

Top comments (0)