React Hooks Tutorial - Understand React Hooks Easy Way


Posted 4 months ago by Ryan Dhungel

Category: React Hooks React

Viewed 529 times

Estimated read time: 6 minutes

Course of the day!

Laravel with Nuxt JS - Build API Driven SSR Vue JS Web Application

Laravel with Nuxt JS - Build API Driven SSR Vue JS Web Application

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.

A simple counter using class component

// src/App.js
import React, { Component } from "react";

class App extends Component {
  // create state
  state = {
    count: 0
  };
  // increment method
  increment = () => {
    // destructure
    const { count } = this.state;
    this.setState({
      count: count + 1
    });
  };
  // render
  render() {
    const { count } = this.state;
    return (
      <div>
        <button onClick={this.increment}>Clicked {count} times</button>
      </div>
    );
  }
}

export default App;

Now lets re-write this counter app using hooks.

A simple counter using useState hook

// import useState hook
import React, { useState } from "react";

// create functional component
const App = () => {
  // useState returns 2 things - current state value and function
  // here count is current state value
  // and setCount is function that will let you update this count state
  // so instead of using setState({count: 1})
  // you will use setCount({count: 1})
  // useState(0) - O is the default value of count
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <button onClick={increment}>Clicked {count} times</button>
    </div>
  );
};

export default App;

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.

A document title setter app using class component

React's useEffect hook

// src/App.js
import React, { Component } from "react";

class App extends Component {
  // create state
  state = {
    count: 0
  };
  // increment method
  increment = () => {
    // destructure
    const { count } = this.state;
    this.setState({
      count: count + 1
    });
  };
  // lifecycle methods - to set html document title
  componentDidMount() {
    const { count } = this.state;
    document.title = `Clicked ${count} times`;
  }
  componentDidUpdate() {
    const { count } = this.state;
    document.title = `Clicked ${count} times`;
  }
  // render
  render() {
    const { count } = this.state;
    return (
      <div>
        <button onClick={this.increment}>Clicked {count} times</button>
      </div>
    );
  }
}

export default App;

It works. We have used 2 lifecycle methods to set the document title on each click. Lets re-write this app using useEffect

A document title setter app using useEffect hook

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

const App = () => {
  const [count, setCount] = useState(0);

  // useEffect - replacing lifecycle methods
  // takes arrow function as argument
  // as the state changes, useEffect runs
  useEffect(() => {
    document.title = `Clicked ${count} times`;
  });

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <button onClick={increment}>Clicked {count} times</button>
    </div>
  );
};

export default App;

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.

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

Awesome. It works!

News App using React Hooks

Now that you understand useState and useEffect, let’s build a HackerNews Client using useState and useEffect.

// App.js
import React, { useState, useEffect } from "react";

const App = () => {
  // state
  const [news, setNews] = useState([]);
  // fetch news
  const fetchNews = () => {
    fetch("http://hn.algolia.com/api/v1/search?query=react")
      .then(result => result.json())
      .then(data => setNews(data.hits))
      .catch(error => console.log(error));
  };
  useEffect(() => {
    fetchNews();
  }, []); // [] means run only when component mounts, not on updates

  return (
    <div>
      <h2>News</h2>
      {news.map(n => (
        <p key={n.objectID}>{n.title}</p>
      ))}
    </div>
  );
};

export default App;

In this tutorial, you learned how useState and useEffect react hooks work.

Build a FullStack React Node Social Network from Scratch to Deployment

By the way, If you are looking to become a FullStack React Node Developer, then you might find this Udemy course interesting. This course starts from scratch and takes you on a journey to build a fully functional Social Network App from Scratch to Production. Cheers!!