React JS React Hooks Use State

The useState hooks let you add state to functional components. In class, the state is always an object. With the useState hooks, the state doesn't have to be an object. the useState hooks return an array with 2 elements. The first element is current value of the state, and the second element is a state setter function. New state value depends on the previous state value then you can pass a function to the setter function.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

1. HookCounter

import React, { useState } from 'react'; function HookCounter() { const [count, setCount] = useState(0); return ( <div> <button onClick={() => setCount(count + 1)}>Count {count}</button> </div> ) }

In above code, we declare a state as count with the help of useState. set initial value to count as 0 by useState(0). Now for setting value in state by - setState(value) - eg. setCount(newcount} and get value in {count}. when we click on button it will add one in current count and show in button text.

Above is the simple code of useState. now, we can use it for array in below example.

import React, { useState } from 'react'; function HookCounter() { const [items, setItems] = useState([]); const addItem = () => { setItem([...items, { id: items.length, value: Math.floor(Math.random()*10) + 1 }]) } return ( <div> <button onClick={addItem}>Add a number</button> <ul> { => ( <li key={}>{item.value}</li> )) } </ul> </div> ) }

When we run above code in browser, then it will show a button. when we click on button - It will add an item in list with. Here, we take item as State and assign an empty array to it by useState([]). when we click on button it will call addItem function and add new item in setItem. for keep previously added item as it is, here we used spread operator '...items'. and add new item having id and value. value is the random number less than 10.


← Previous

Next →