Codementor Events

React Hooks for Beginners

Published Sep 10, 2024
React Hooks for Beginners

Start writing here...## What are Hooks in React?

React introduced Hooks in its 16.8 release, and with it came the ability to use more of React's features without having to use classes.

This is not saying that classes are no longer used, or that they are becoming deprecated(at least not yet) so there is no need to rush in updating all of your classes into functions.

Hooks were designed with this in mind and work side-by-side with existing code which allows for a gradual adoption process...no rush.

How Do They Work?

Typically when dealing with State in a React class you would have something like this:

This example renders a button that when clicked increments the value of 'jumps' by one.

import React from 'react';

class JumpMan extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      jumps: 0,
    };
  }
  render() {
    return (
      <div>
        <p>You jumped {this.state.jumps} times.</p>
        <button onClick={() => this.setState({ jumps: this.state.jumps + 1 })}>
          Jump Again!
        </button>
      </div>
    );
  }
}

And in order for your class to have its own state, you would need to pass it into a <mark>constructor</mark> method on the instance (<mark>this</mark>), invoke <mark>super</mark> so you can use <mark>this</mark>, and pass in 'props' as an argument to <mark>super</mark>.

Then with the release of class fields you no longer had to use a <mark>constructor</mark> to set the initial state of the component so your new class would look something like this:

import React from 'react';

class JumpMan extends React.Component {
  state = {
    jumps: 0,
  };

  render() {
    const { jumps } = this.state;
    return (
      <div>
        <p>You jumped {jumps} times.</p>
        <button onClick={() => this.setState({ jumps: jumps + 1 })}>
          Jump Again!
        </button>
      </div>
    );
  }
}

Although this is cleaner, you are still having to use a class in order to have and manipulate your components state.

With Hooks this is no longer necessary. You can now turn your class into a function and use a hook called "useState" which will return a pair: the current state and a function that lets you update it! Then just pass in the initial state as an argument to useState and that's it!

You can then call this function just as you would call this.setState like I am doing here:

import React, { useState } from 'react';

function JumpMan() {
  const [jumps, setJumps] = useState(0);
  return (
    <div>
      <p>You jumped {jumps} times.</p>
      <button onClick={() => setJumps(jumps + 1)}>Jump Again!</button>
    </div>
  );
}

Also, you can have multiple state objects if you need to like so:

const [jumps, setJumps] = useState(0);
const [highFive, setHighFive] = useState(0);
const [kicks, setKicks] = useState(0);

Not only does this new hook clean up the code a bunch, but it also simplifies things by not having to write class components.

But Wait Theres More

The way you handle state in your components wasn't the only thing on React's radar during this time. They also wanted to change how you handle side effects such as changing the DOM from your component or data fetching.

To solve this React introduced a Hook called "useEffect".

This now gives us the ability to perform these side effects within a function component! Gone are the days of setting up a class component in order to achieve the same effects with <mark>componentDidMount</mark>, <mark>componentDidUpdate</mark>, or <mark>componentWillUnmount</mark>....welcome to cleaner React!

So how does this look?

Going back to our previous JumpMan example we will add in useEffect to set the document title after React updates the DOM!

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

function JumpMan() {
  const [jumps, setJumps] = useState(0);

  useEffect(() => {
    document.title = `You have jumped ${jumps} times! Keep Going!`;
  });

  return (
    <div>
      <p>You jumped {jumps} times.</p>
      <button onClick={() => setJumps(jumps + 1)}>Jump Again!</button>
    </div>
  );
}

Here, useEffect runs after every render and is being used in place of <mark>componentDidMount</mark> and <mark>componentDidUpdate</mark>! One thing to keep in mind when using this Hook is that it must be declared within the component so that it will have access to its props and state.

What Are The Rules

Hooks are meant to only be called at the top level, don't try and call them inside loops or conditions because it won't work.

Also you can only call Hooks from React function components or your own custom Hook. If you try and call inside a class or regular JS function it won't work. To learn more about these rules or Hooks in general checkout React's official documentation.

I hope this has helped give you a brief introduction into the world of React Hooks!

If you have found this post helpful, checkout my weekly newsletter that I send out to hundreds of other developers to help them level up and make more money!

Discover and read more posts from Travis Ramos
get started