React Hooks 😍

React Hooks 😍

Let’s dive in and get a better understanding about react hooks

Table of contents

No heading

No headings in the article.

image.png

What are Hooks?πŸ€”

Hooks are specially-implemented functions that let us add functionality to React components beyond just creating and returning React elements.

We’ll look at some of the react hooks in this article 🧐

useState - Persist state within a component function

useReducer - Similar to useState, but for a state that involves multiple sub-values

useEffect - Perform side effects within our component functions

Let’s start with useState hook πŸ˜‡

The useState hook lets us "remember" a value within a component function. Since our component function may be called many times throughout the lifecycle of the component, any variable we declare normally (i.e. with let myVar = ...) will get reset. With useState, React can remember a state variable for us, making sure it gets passed into our component instance correctly.

The useState hook takes a single argument, our initial state, and returns an array containing two elements:

state - the current state

setState - a function to update our state

E.g. const [state, setState] = useState(initialValue)

The useState hook can store any type of value: a number, a string, an array, an object, etc.

Example

image.png

Awesome! We start with an initial state of 0 and when we click on the button we see the count value will increase by 1.

Easy right??πŸ˜€

Yeah, it’s super easy and a really important react hook. I hope it will help you see you in the next article with other react hooks.

Thank you πŸ™

Did you find this article valuable?

Support ATUL KUMAR SINGH by becoming a sponsor. Any amount is appreciated!

Β