useState hook in React

useState hook in React

Usage of useState hook, map and filter function in ReactJS

Table of contents

No heading

No headings in the article.

Hooks: Hooks are the way to write reusable code rather than using the more classic approach of inheritance in react

Rules for the hooks:

  • Don’t call inside loops
  • Don’t call inside conditions
  • Don’t call inside nested function
  • Always use hook at the top of the function
  • Only call hook from the react function

Primitive hooks (which are mostly used in react):

  • useState()
  • useEffect()
  • useRef()

useState hook

Important: For multiple states useState hook is used multiple times.

To use the hooks in react, we need to import them first and do so we need to import them from react as shown below.

import React,{useState} from 'react';

Here we have successfully imported the useState hook and now we can use this hook to track the different state changes in our application

const [age,setAge] = useState(21);

Important: variable age is known as getter function and setAge is known as setter function

The default value that age has is 21, and we can change that value by using our setter function i.e. setAge and we can do so by setAge(22).

Other important utilities used in React

Filter function in react

Filter function is used to filter out the certain items from the bigger dataset, the filter function does not affect the original dataset from which we are filtering out the items, rather it returns the new modified dataset [filtered data set] which we can use

const [age,setAge] = useState([1,2,3,4,5,6,7]);
const filteredAge = age.filter(a => a<5)

console.log(filteredAge);

Here in the above example we are filtering the age array based upon the condition < 5, so all the items in the array named age will be filtered and returned to a new array named as filteredAge and this array will contains the items as 1,2,3 and 4 only

Map function in react: We do not use for loop in react rather we use map function to iterate over the multiple items. In addition, we have 2 approaches to use map function, one with return statement and other without return statement.

Using map without a return statement

const [age,setAge]=useState([1,2,3,4,5,6,7,8,9]);
age.map((a)=>(<p>{a}</p>))

Using map with a return statement

const [age,setAge]=useState([1,2,3,4,5,6,7,8,9]);
age.map(a => {
  return <p>{a}</p>
})