top of page
Search

What are React Hooks?

Writer's picture: Titash RoyTitash Roy

Introduction

Prior to React 16.8, state can be associated with class components only. And it is the class components that can interact with the redux store. From 16.8, react hooks were introduced, that allow us to use state functionality in the functional components as well. Below is a snippet on how to use hooks. useState() is one of the most important hooks. We will discuss about various important hooks in details.


Rules to write Hooks

Hooks are similar to JavaScript functions. The rules ensure that all the stateful logic in a component is visible throughout the source code. Below are the rules followed while writing Hooks:

# Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.

# Only call Hooks from React functional components. Don’t call Hooks from regular JavaScript functions. There is another place from where the hooks can be invoked, by creating custom hooks[We will discuss them in the subsequent blogs].


useState hook

This hook is used for manipulating the state in a class. Given a default state, the syntax for useState is as const[state, setState] = useState(defaultState).

In our example, we would increase and decrease the age using the useState hook. Below is the code snippet:

In the code snippet above, the age is a variable and initially takes the default state mentioned under the useState(). The function setAge is used to set the age inside the _decreaseAge() function. The setAge() does the same work that the setState method does in class components.

But we can update an attribute inside state using hooks, directly, we needn't create a copy object of the state and then merge the changed attribute as done in case of setState().


Summary

In this blog, we had an introduction to React Hooks and learnt about one of the most important hooks, useState. In the next blog, we will discuss about other frequently used React Hooks, useEffect, useReducer, useRef.


12 views0 comments

Recent Posts

See All

Comentários


bottom of page