DEV Community

builtbyjosh
builtbyjosh

Posted on

Quick look at useState()

Another powerful function that is becoming very popular with functional components is the useState hook. The useState hook allows you to share state with functional components. With this hook, you can quickly add state to a function component without having to convert it to a class component.

The way you would normally declare state in a class component would look like this:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0;
        };
    };
};
Enter fullscreen mode Exit fullscreen mode

A constructor class is required to create the initial state in a class component. This leads a lot of boiler plate code and what could be written in just a couple lines is now almost 10 lines. To do the same thing with a functional component and the useState hook, you must first import the hook into you file and then declare the state as a new variable:

import React, { useState } from ‘react’;

const example = () => {
    const [count, setCount] = useState(0);
};
Enter fullscreen mode Exit fullscreen mode

In this example we declared the new variable as count and set it to 0. We then created a setter variable called setCount so we can reference the state and manipulate it later. Normally in a class component, state is changed like this:

this.setState({ count: this.state.count + 2 });
Enter fullscreen mode Exit fullscreen mode

But since we created a setter variable, you change the state like this:

setCount(count+2)
Enter fullscreen mode Exit fullscreen mode

Since useState is used inside of a functional component, you also access the saved state slightly differently. Within a class component, you would call it with ‘this.state.count’ but within the functional component, you only have to reference ‘count’.

Just like with class components, you can set many different state variables using useState, you just have to follow the same pattern as the first state variable declared.

const [car, setCar] = useState('chevy');
const [snack, setSnack] = useState('cookies');
const [todo, setTodo] = useState({text: 'Take out trash'})
Enter fullscreen mode Exit fullscreen mode

You can set the value of the state to any normal variable type in react. Strings, booleans, numbers, even objects. So as you can see the useState hook allows you to quickly switch to functional components and avoid using Redux. This can cut down the amount of code you have to write as well.

Top comments (0)