Getting Started with React Hooks

wulforr

Shaurya Vardhan Singh

Posted on December 2, 2020

Getting Started with React Hooks

This guide is for people who are just starting with React and want to know what hooks are and learn about some important hooks.
If you are learning React, hooks will become an integral part of your life. There are a total of 10 hooks in React but other than some special cases you will use only 2-3 hooks in day to day coding.
So, let's get started.

What is Hook?

According to React docs -

A Hook is a special function that lets you โ€œhook intoโ€ React features.

Hooks were added in React 16.8 and it lets you add state and other functionalities in function based component, earlier which was possible only in class based components.
So, lets take a look at most used hook first.

1) useState Hook

useState Hook is the most commonly used hook. It is used to add a state to the functional component.
Lets look at a example that shows current Age of user and on clicking on button it adds 1 year to current age.

import React, { useState } from 'react';

function Example() {
// using the useState hook to store age.
const [age, setAge] = useState(0);
  return (
    <div>
      <p>You are of {age} years</p>
      <button onClick={() => setAge(age + 1)}>
        Click me
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

so whats happening here:

  • In line 1 we are importing the useState hook.
  • In line 5 we are declaring the age variable as state and initializing it to 0. We are also making a function setAge to update the age.
  • In the paragraph we are displaying the age by using the javascript syntax in jsx.
  • The onClick on button sets the age to age+1, this will rerender the component.

for using multiple state variables inside a component you can create multiple useState -

const [age, setAge] = useState(0);
const [name, setName] = useState('React');
Enter fullscreen mode Exit fullscreen mode

here we have 2 state variables age and name and both have their setter functions setAge and setName respectively.

2) useEffect Hook

useEffect hook is another important hook and is used mainly to run some code on mounting of component or whenever some dependency changes.

Let's look at an example of useEffect hook. Here we are setting the title of document on each render.

import React, { useState, useEffect } from 'react';

function Example() {
const [age, setAge] = useState(21);
const [name, setName] = useState("Shaurya");

useEffect(() => {
  document.title = `${name} is ${age} years old`;
})

  return (
    <div>
      <p>Shaurya is {age} years old</p>
      <button onClick={() => setAge(age + 1)}>
        Click me
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example we are executing useEffect hook on each render, but our title is only changing when age is changed.

For such cases we can add a dependency array to useEffect hook and only when one of the dependency changes then only the useEffect hook will be executed.

useEffect(() => {
  document.title = `Shaurya is ${age} years old`;
},[age])
Enter fullscreen mode Exit fullscreen mode

Here we added age to the dependency array so whenever age is changed useEffect will be executed.

In this example we are executing our hook on the value of age but what if we only want to execute our hook once. For example making a request to an API.

In such cases we can pass an empty dependency array and then the useEffect hook will only be executed once.

useEffect(() => {
  document.title = `Shaurya is 21 years old`;
},[])
Enter fullscreen mode Exit fullscreen mode

Further Reading -

These two hooks are most important and if you have a good grasp on these then you can tackle 95% of cases. In 5% of cases other hooks are used, in which mainly useRef(to select any dom node) and useContext hooks are used all the other hooks are used very rarely.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
wulforr
Shaurya Vardhan Singh

Posted on December 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About