Eman's Blog


Eman's Blog


React - Hooks

Eman's photo
ยทSep 23, 2021ยท

2 min read


React - Hooks at a glance

React Hooks are in-built functions that allow React developers to use state and lifecycle methods inside functional components, they let you use React without classes. ... You can also create your Hooks to reuse stateful behavior between different components.

In this post, we will be learning about the following react hooks.๐Ÿ“”

  1. useState()
  2. useEffect()

1 - UseState () ๐Ÿช

The useState hook lets you add state to function components. We call it inside a function component to add some local state to it.


Step: 1 You need to import the useState hook from the react library.


Step: 2 You need to have something to store data using useState, it is the name of the state variable, and a variable to set the state (updating the value stored in the state).


That is the conventional way of using the useState hook. "name" is the name of the state variable, and setName is a method to update the state variable.

It is a good practice to name that with the word set together with the name of the state variable. Now, I have passed empty strings inside of useState(), which means that I want the default value of the variable name, to be equals to nothing and the type of the variable to be a string.

You could change the value of the variable name like Jhon, Raza, or Yuri... carbon(3).png

You could call this method inside of a function, or on a button click, or any way. That is the useState() hook.

Now let's get to the other type of hook.

2 - UseEffect() ๐Ÿช

UseEffect is a hook that allows you to run a piece of code only when something happens. It would execute side-effects in React components. For example, you would want to make an API call only when the user changes the search input., etc. First, you would import useEffect() as always.

carbon(4).png For Example, you want to console log the input value every time the user changes the input.


We are using an arrow function that console logs the input of the user every time there is a change in the input value.

carbon(6).png The above code means you want to run the piece of code inside of the useEffect hook only once when the website loads.


That Was a quick introduction to hooks that are used more often. Please give feedback/suggestions or ideas so I can make my next article better l would appreciate it.๐Ÿ˜Š

Share this