React Hooks Tutorial - Understand React Hooks Easy Way

Course of the day!

React with Node JS Social Network from Scratch

React hooks lets us use state and other react features without writing class components. With the introduction of react hooks, you can clearly see that react is moving closer towards functional programming. The official react documentation says about hooks:

Hooks are functions that let you “hook into” React state and lifecycle features from function components.

Why we were using class components?

We had to use class components for following reasons:

To keep data in state

To use lifecycle methods

To pass props from classes to functional components

However with react hooks, we can do all this without writing class components. Lets begin by creating a simple counter example using class component. Then we will re-write this using react hooks. You can use create-react-app to generate a new react app and follow along with this tutorial.

Using useEffect hook

In class based components, you would use lifecycle methods such as componentDidMount or componentWillMount. On functional components you can now use useEffect hook to handle such side effects (changed state etc).

As the state changes or updates, useEffect will run.

To better understand useEffect hook, lets build a simple app that will let you update the document title. You can see the document title changed on the browser tab, beside a favicon.

Learning a bit more about useEffect hook

You can run more than one function inside useEffect.

useEffect runs each time the state changes.

In bigger apps, state will contains many properties. You surely dont want to run all the methods inside useEffect all the time. To be more explicit about when to run useEffect, you can pass an additional argument to useEffect. Here I have added empty array.

With this change, if you run the document title setter app. You dont see the document title changed. Thats because we have passed nothing to []

useEffect(() => {
document.title = `Clicked ${count} times`;
}, []);

To ensure the document title updates on count, pass count to the array.