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';
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 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);
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.
Thank you for reading my blog. Feel free to connect on LinkedIn or Twitter :)
Top comments (3)
Interesting read.
Facing a challenge and need your support on authinticating JWT in react native. After login, the generated token should be used to give acces to private pages. However, after implementing this, the middleware responds with an invalid or expired token provided error. I've hit a dead end troubleshooting. Kindly help. Thank you. kind regards, Ngotho Joseph.
Nice read. Please write about other hooks with similar examples.
Thank you, will do :)