React Hooks useState understanding.

Hooks useState

In this article, I will explain about react Hooks useState.

A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to functional components.

Why we need Hooks?

Reuse stateful login between react component.

Earlier whenever we use the setState method, we want to use React class component. Using Hooks useState method we can use the setState method in functional component.

To solve this problem, Hooks let you split one component into smaller functions based on what pieces are related.

How do Hooks useState work?

import React, { useState } from "react";export const Hooks = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>you clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};

This is the basic example of hooks. In this example, we can increase the count value using the useState method.

But earlier if we want to use this.state method we need React class. The above example also works like this.state method.

There is only one argument to useState that is the initial state. In this example given above, the initial state is 0 because our counter starts from zero.

function ExampleWithManyStates() {  
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...}

Rules of Hooks

Hooks rules.l
  • Only call Hooks at the top level. Don’t try to call Hooks inside loops, conditions, or nested functions.
  • Only call Hooks from React function components. Don’t try to call Hooks from regular JavaScript functions.

Happy learning……..

Reference blogs:

Software developer / JavaScript / React / React Native / Firebase / Node.js / C Programming / Book Reader / Story Teller