React Hooks - Getting Started

An in-depth introduction to Hooks in React

·

4 min read

React Hooks - Getting Started

Introduction to Hooks

Hooks have become ubiquitous in the React ecosystem because of how indispensable they are. However, it can sometimes be confusing (especially for beginners) to know which one to use and the best way to go about it.

If you are a beginner in React, chances are that you only know how to use functional components (compared to class components), and you've probably heard of (and maybe used) hooks in React. But what exactly are hooks? According to React's documentation:

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

But what does this really mean? To fully understand this requires a good understanding of the basics of JavaScript.

One of the fundamental characteristics of functions in any programming language is that they are reusable. So in JavaScript, a function is a reusable piece of code for performing repetitive tasks. Functions are composable, meaning you can invoke a function in another function and use its output.

function myFunc() {
    console.log("My Func ran")
}

// another function
function newFunc() {
    console.log("New Func ran")
    myFunc()
}

In the example above, if we invoke newFunc we get New Func ran as well as My Func ran in the console; this is because we invoked myFunc inside newFunc.

There are two types of functions in JavaScript:

  • Pure Functions: These are functions that do not have side effects. This basically means that, no matter how many times you run the function, it doesn't change the state of the application and will always return the same output. These can also be called Stateless functions. The two functions above are examples of pure functions.

  • Impure/Stateful Functions: These are functions that affect the state of the application. For example, if you have a function that takes an argument and changes the value of that argument, that is an impure function.

let   numOfUsers = 1

// increase number of users
function increaseNumOfUsers() {
    numOfUsers += 1
}

In the example above, each time we invoke the function, it changes the value of numOfUsers.

React Hooks and Stateful Logic

Hooks are functions that allow you to add stateful logic (i.e. code that changes the state of your application) to your functional components.

With React Hooks, we can isolate stateful logic and side effects from a functional component. Hooks are JavaScript functions that manage the state's behavior and side effects by isolating them from a component.

Hooks provide most of the functionalities that were only available with class components. In other words, hooks allow you to maintain the state and lifecycle of your application without the need to use classes.

Types of Hooks

There are fifteen hooks in React v18, some of which are not very common because of their rare use cases. You can also create your own custom hooks (more on this later). The following are the different types of hooks, which we are going to talk about one after the other subsequently:

Basic Rules For Using Hooks

There are two basic guiding rules for using hooks in React:

  • Hooks can only be called at the top level. Don’t call Hooks inside loops, conditions, or nested functions.

  • Hooks can only be called from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks — custom Hooks, which we’ll learn about later.)

// import the hook
import { useState } from 'react';

function GoodExample() {
  // hooks are initialized at the top of the function
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
// import the hook
import { useState } from 'react';

function BadExample() {

  return (
    <div>
        {// this will throw an error}
       const [count, setCount] = useState(0);
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

One other thing which you should also be aware of is that hooks only work in functional components. If you are using classes then you don't need hooks.

Good to Know

With the advent of hooks in React, there's very little reason to stick with class components as hooks provide most of the features that previously required class components. However, if you prefer using classes instead of functions, then it's perfectly okay to stick to it as the documentation states that there is no plan to scrap out classes in the foreseeable future. Hooks are not a replacement for classes, they are meant to be an alternative (a more cleaner alternative in my opinion). I would honestly love to hear from you if you used/still use classes, which do you prefer and why?.

Conclusion

This is the first article in this series. Subsequently, I'll be writing about all the various hooks listed above and also how you can create your own reusable custom hooks. I will also be updating this article with links to future articles in this series. Don't forget to subscribe to my Newsletter to get notified about future articles.

Did you find this article valuable?

Support Paul Saje by becoming a sponsor. Any amount is appreciated!