Basic Hooks in React - useState()

Olena Drugalya - Jan 8 '21 - - Dev Community

This blog post continues the series about React Hooks.

Here we are exploring one of basic and most important hooks in React - useState().

What is useState()?

useState() is JavaScript function, which is used in functional components to crate state and access it. To use this hook, you need to import it first from React library like this:

import {useState} from 'react';
Enter fullscreen mode Exit fullscreen mode

You can use this hook without import as well like this - React.useState(), for me it's just more convenient to import and destructure first this function and then use it when need in the code.

How to use

We call this hook like this:

const [state, setState] = useState(initialState)
Enter fullscreen mode Exit fullscreen mode

This hook returns 2 values - stateful value and the function to update it.

The first returned value is state - this is the data we pass to hook as initialState parameter.

The second returned value is setState - this is a function which is used to update the state.

Characteristics and tips you should know

  • returned values from useState() can be called as you want. Its a good practice to call them with meaning, for example if you are building a Counter app, it's good to give state a meaningful name:
const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode
  • by calling useState() inside a function component, you create a single piece of state associated with that component.

  • the state can be any type you want – you can useState() with an array, useState an object, a number, a boolean, a string, whatever you need.

  • you can create multiples states in one component according to data which they hold:

  const [items, setItems] = useState([]); // array
  const [itemName, setItemName] = useState(""); //string
Enter fullscreen mode Exit fullscreen mode

This hook is especially useful for local component state, but larger projects might require additional state management solutions.

Thank you for reading my blog. Feel free to connect on LinkedIn or Twitter :)

Buy Me a Coffee at ko-fi.com

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .