Hooks in ReactJS

hooks-in-reactjs

Hooks in Reactjs: Hooks are a new addition in React 16.8. They allow you to use React without classes. It means you can use state and other React features without writing a class.

Hooks are functions that let you “hook into” React state and lifecycle features from function components. React provides a few build-in Hooks like useState, useEffect, etc.

When use Hooks:

If you write a function component and realize you need to add some state to it.

Rules of Hooks:

  1. Only call Hooks at the top level:- We should always use Hooks at the top level of your React function. We should not call Hooks inside loops, nested functions or conditions.
  2. Only call Hooks from React Functions:- We should not call Hooks from a regular javascript function. Instead, call Hooks from React function components or call Hooks from customer Hooks.
  3. React relies on the order in which Hooks are called.
  4. Hooks don’t work inside classes.

Declaring State:

useState():- useState is a Hook that allows you to add React state to function components. We call it inside a function component to add some local state to it. useState returns a pair – the current state value and a function that allows us to update it. We can call this function from an event handler or somewhere else. React will preserve this state between re-renders.

When we declare a state variable with useState, it returns a pair – an array with two items. So, by Writing the square bracket we are doing Array Destructuring.

Example:-

name = It is the current value;
setName = It is a function that allows us to update it.

Note: – You can call useState as many times as you want.

Declaring multiple state variable:

Accessing State:

In a function, we can use a state variable directly. As in class-based component, we need to use this.state.value, but in function component, we don’t need to use this.state.

Updating State:

We will use the second item from a pair of the array as a function to update State value.

Ex: –

Let’s understand all the above point using a complete coding:

In the above code, you can see that we declare the state as name and age. Also, we created a button “Click Me” using an onClick event handler “btnClick”. When we click on button then name and age state value will set using btnClick function. After this, the value of name and age state value will return and reflect on the screen.

Effect Hooks in ReactJS

Component Mounting Lifecycle Methods in ReactJS

Component Updating Lifecycle Method in ReactJS

What are Web Services?

Related posts