Learn React Hooks In 15 Minutes

Share:


Source Code

What are Hooks?

Hooks provide developers the ability to tap into React’s states and life cycles from anywhere.  It simplifies your components by eliminating boilerplate codes (super(props), componentDidMount, function binding, etc).  Hooks also allows you to encapsulate powerful logics into custom hooks and reuse them throughout your application.

  • Completely opt-in. You can try Hooks in a few components without rewriting any existing code. But you don’t have to learn or use Hooks right now if you don’t want to.
  • 100% backwards-compatible. Hooks don’t contain any breaking changes.
  • Available now. Hooks are now available with the release of v16.8.0.

useState Hook

the useState hook is the replacement for setState.  The API allows you to define a state variable and setter function with one call.

const [cartItems, setCartItems] = useState([]);

This statement means I want to define a state variable call cartItems and a setter function setCartItems with the default value of cartItems set to []

The beauty of this is that it does 3 things in a single statement!  Let’s see a real example using useState:

import React, { useState } from 'react';
import logo from './logo.svg';
import './App.css';

export default function App() {
  const [cartItems, setCartItems] = useState([]);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>Items in your cart: {cartItems.toString()}</p>
        <button
          onClick={()=>{
            setCartItems([...cartItems, 'apple'])
          }}
        >Add to Cart
        </button>
      </header>
    </div>
  );
}

As you can see, with hooks, this whole example can be written in few line.  The key piece of code to look at is when we set the onClick handler of the button: we’re calling setCartItems() setter by passing in the desired value we would like to set cartItems to.

useEffect Hook

The useEffect hook is used when you have want to execute something that resulted in “side effects”, what are side effects? I’ll borrow the definition from the official site:

Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. Whether or not you’re used to calling these operations “side effects” (or just “effects”), you’ve likely performed them in your components before.

So, we want to call useEffect whenever we want to do any of the things mentioned above.

Let’s take a look at an example:

useEffect(() => {
    window.addEventListener('scroll', determineUserScrollDepth);

    return function unbindScrollListener() {
      window.removeEventListener('scroll');
    }
  });

The api takes a function callback as the first parameter, and an optional conditionality array as second parameter (will get to that later).

To put it simply, you want to put anything you would typically put in compontDidMount, componentWillUnmount or componentDidUpdate into this hook.  In the example above we attached an event listener to window’s scroll event when the DOM has rendered.

Notice there’s a function returned within the useEffect hook, this is a optional, but when you do return it, React will call this function when the component unmounts, so you would put your cleanup code in there.

Now let’s talk about the optional second parameter of useEffect, this parameter takes an array of things you would like the effect to watch so it will only update when that value changes.  If you omit the param or pass in an empty array, then the code inside useEffect will only get called when the component mounts or unmounts.

Here’s a full example of a component that prints out user’s scroll position as they scroll the page up or down:

import React, { useState, useEffect } from 'react';
import logo from './logo.svg';
import './App.css';


export default function App() {
  const [scrollDepth, setScrollDepth] = useState(0);

  function determineUserScrollDepth() {
    const scrolled = document.documentElement.scrollTop || document.body.scrollTop;
    setScrollDepth(scrolled);
  }
  useEffect(() => {
    window.addEventListener('scroll', determineUserScrollDepth);

    return function unbindScrollListener() {
      window.removeEventListener('scroll');
    }
  });

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        You've scrolled this far: {scrollDepth}

        <p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
        </p>
      </header>
    </div>
  );
}

As you can see, hooks made the code so much simpler to read and understand, you’ll no longer write any boilerplate code relate to classes when you write React.  The caveat with hooks is that you cannot use hooks inside Class based components, and you can only call hooks on highest scope, meaning you cannot put hook calls inside of conditions like if or for loops.  You can read more about that here

I hope this serves as a light introduction to Hooks for you, head over to the official site to get more details about how Hooks work.  I look forward to hear what you guys think about hooks and what you come up with.

You Might Also Like

Error, group does not exist! Check your syntax! (ID: 7)