React Hooks

Md Farhad Hossain
2 min readOct 17, 2020

--

What is react hooks?

Hooks are a new addition in React 16.8. It allows you to use state and other React features without writing a class
Generally hooks are functions which “hook into” React state and lifecycle features from function components. The most commonly used react hooks are useState, useEffect, useContext. In this article we’ll briefly talk about useState with a simple example.

What is useState?

useState is a react hook that let us update a state of a functional component. It holds two values one the current state value and a function that allows you to update it.

How to use useState?

To use useState , first you’ll need a React app. If you already have open your app in a code editor. Or to create an app use this command

npx create-react-app react-hooks-app

To change the directory and open your app run-

cd react-hooks-app
npm start

Now you have to import useState from react and declare a state

As you can see we declare the state with an initial value 0, Here we use

[count, setCount]. It’s not a naming convention of useState API. You can use any name but make sure it makes sense, anyone reading your code can easily understand what the state means stand for. Here I prefer when we declare a state is name would be like [stateName, setStateName]. Let’s see the full example

In this example when you click the button (click me) it will automatically update the state value and set it to count. That means every click it will increase the count value = previousValue + 1.
Look how simple it is. You can use it not only for counting even you can use it in any function where you have to update state.

--

--

Md Farhad Hossain
0 Followers

Technology enthusiast, diligent and has a great ability to learn something new quickly. Obviously a good human being and affable.