Basic Hooks in React – useState()

Basic 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';

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)

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 initialStateparameter.

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);
  • 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

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

from Tumblr

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s