Understanding useState Hooks in ReactJs with an Easy Example

·

3 min read

In this blog, we'll see what are hooks in Reactjs, where are they used, and an easy example of useState hooks to understand it better. Let's jump in Screenshot 2020-11-03 at 1.21.46 AM.png

What are hooks?

Hooks are nothing but State which lets you change information of a component. While State is used with classes, Hooks are used in functions.

Some famous in-built hooks are:

  • State Hook
  • Effect Hook

Important points to remember

  • Don’t call Hooks inside loops, conditions, or nested functions.
  • Component names should be uppercase
  • Hooks must be in a function/component body not class
  • You can use more than one hook in a function

What is useState used for?

You use State Hook if you want to change a state of a component inside a function. It can increase or decrease a value, Change the string or data, etc.

Let's code a small Example

Import useState
import React, { useState }  from 'react';
Declare Function
const MyFunction = () =>{
    return (
    <React.Fragment>
      <h1>{text}</h1>
      <button>Change Title</button>
    </React.Fragment>
    );
};
}
Declare a useState in function

Below line will assign text value of 'Original title'

const[text, setText]=useState('Original title')

Now add a button in function to change the title

 <button onClick={handleClick}>change title</button>
Declare function handleClick inside MyFunction
const handleClick = () => {
    console.log('Testing')
}
To change a text we use setText. Remember text stores the most recent update.
setText('Title changed')
Add this inside handleClick
const handleClick = () => {
    setText('Title changed')
}
You can add conditional logic like this:
 const handleClick = () => {
    if(text=== 'Original title'){
        setText('Title changed')
    }
    else{
      setText("Original title")
    }
}

Final Code

import React, { useState }  from 'react';
const MyFunction = () =>{
    const[text, setText]=useState('Original title') 

    const handleClick = () => {
        if(text=== 'Original title'){
            setText('Title changed')
        }
        else{
        setText("Original title")
        }
    }
    return (
    <React.Fragment>
      <h1>{text}</h1>
      <button onClick={handleClick}>change title</button>
    </React.Fragment>
    );
};
}

You can also use arrays and objects with useState:

Arrays

const data = [
  { id: 1, age:23 },
  { id: 2, age:19 },
  { id: 3,age:28 },
  { id: 4, age:87 },
];

const [people, setPeople] = useState(data);

Objects

 const [person, setPerson]= useState({
    name:"yash",
    age:21,
    message:'Keep Coding'
 })
You can use the map function to render Arrays and objects

Important Resources

SourceLink
DocumentationHere
What are hooksHere
What are StatesHere

Stay tuned for more such articles on React. Let me know if you like it. Thanks.

You can Follow Me Here