React Hooks — Made Simple

React Hooks — Made Simple

React Hooks are the hot new thing to React, and they are very beneficial when you start to use them in your applications. Not only that, but they’re very easy to understand and implement.

1_-Ijet6kVJqGgul6adezDLQ.png

Why did we need React Hooks

What was wrong with the old way of doing things with lifecycle methods, and using the constructor to manage state?

  1. Using lifecycle hooks made React components very cumbersome and large. Often times your smart components would have two to four lifecycle methods which could add upwards of 40 or 50 lines per component. Using hooks will help you to reduce a portion of those lines to accomplish the same thing.
  2. The function setState is something i’m sure you’re very aware of. Although there was inherently nothing wrong with using setState and using the constructor to create state, the way React Hooks implements its replacement is (in my opinion) better because it’s declarative in specifying the specific pieces of state that you’re interacting with, and it reduces the amount of boilerplate code used in each component. We’ll dive more into this below!

So what really are hooks? React Hooks are built in functions that we can utilize to accomplish ‘lifecycle-like’ functionality and state management within a component. The two that you absolutely need to know are UseState and UseEffect. Let’s dive in:

useState

The useState function replaces the way we used to create state and set state in an old React component. That would look something like this:

class PrincessBrideComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Inego Montoya'
    };
  }
  componentDidMount() {
    this.setState({ name: 'Inego Montoya' });
  }
  render() {
    return (
      <div>
        <h2>My name is {this.state.name}. You killed my father.
          Prepare to die.</h2>
      </div>
    );
  }
}

We’d create the structure of state within the class constructor, then throughout the component we would interact with state using this.state and this.setState({ someProperty: someValue }) .

With hooks, instead of setting the entire state structure within the component’s constructor, we create it piece by piece like the below.

import React, { useState, useEffect } from 'react';
function PrincessBrideComponent() {
  const [name, setName] = useState('');
  const updateName = () => {
    // We can use the setName function to update `name` in state 
    setName('Inigo Montoya');
  }
  return (
    <div>
      <h2>
        My name is {name}. You killed my father. Prepare to die.
      </h2>
    </div>
  );
}

As you see, we create a property in state called name which is now a public variable in the component, and we also create a function called setName which we can use to interact with the name property. It’s as easy as that!

useEffect

The useEffect function replaces lifecycle methods. Old React components would look something like this:

class PrincessBrideComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ''
    };
  }
  componentDidMount() {
    this.setState({ name: 'Inego Montoya' });
  }
render() {
    return (
      <div>
        <h2>My name is {this.state.name}. You killed my father.
          Prepare to die.</h2>
      </div>
    );
  }
}

If we want to replace the above with React Hooks, it would look like this:

import React, { useState, useEffect } from 'react';
function PrincessBrideComponent() {
  const [name, setName] = useState('');
  // Below we use the 'useEffect' hook to replace all lifecycles
  useEffect(() => {
    setName('Inigo Montoya')
  }, [])
  return (
    <div>
      <h2>
        My name is {name}. You killed my father. Prepare to die.
      </h2>
    </div>
  );
}

So what is really happening in useEffect? You can visualize it as a function that runs 1) when the component is loaded, and 2) when any value in the array changes. In our case, we’ve got an empty array which means this function will only run once, ever.

Below is an example of a useEffect which will update every time the prop name changes.

import React, { useState, useEffect } from 'react';
function PrincessBrideComponent({ name }) {
  const [visibleName, setVisibleName] = useState('');
  // This useEffect will run once at the start, then will run again 
  // every time 'name' is a new value
  useEffect(() => {
    setVisibleName(name)
  }, [name])
return (
    <div>
      <h2>
        My name is {visibleName}. You killed my father. Prepare to die.
      </h2>
    </div>
  );
}

Conclusion

React Hooks help us to reduce boilerplate code, and generally help us to be more declarative and functional in the way we write React code. If anything above is confusing or I can clarify in any way, please let me know! :)

I write often on many different programming topics. Let me know what else you’d like to learn!