The useState Hook in ReactJS

State: hooked.

Dhanesh Budhrani
Geek Culture

--

Just a big fat hook. [Image source]

In this post I’ll be making a quick intro to the useState hook, as well as giving some tips when using it.

useState basics

The useState hook is the most commonly used hook in ReactJS, and helps us with two things:

  • It preserves the value of a variable between renders.
  • It helps us easily re-render our component.

Now, how can we use it? First, we need to import it from the ‘react’ package. We may do this in two different ways: using a named import or accessing from the default export of ‘react’.

The named import would be done as follows:

import {useState} from 'react';...const [value, setValue]= useState(0);

While the second method would be done like this:

import React from 'react';...const [value, setValue]= React.useState(0);

You may have noticed that I’m giving one argument to useState (in this case 0), and deconstructing the result in two variables. The argument that we give to useState is the default value of our variable (our initialization value). The returned variables are, the first: the variable…

--

--

Dhanesh Budhrani
Geek Culture

Multidisciplinary software engineer. Constantly learning. Software Engineer@Wubook. MSc@DTU. BSc@UC3M. LinkedIn: https://www.linkedin.com/in/dhanesh-budhrani/