A Look At React Hooks: Introduction

A Look At React Hooks: Introduction

Welcome to A Look at React Hooks, a beginner-friendly series on React Hooks. The purpose of this series is to gather and document some awesome Hooks that are not in the official React documentation. Hopefully, by including these Hooks, more developers can know about them and use them.

First, for the beginners, we will explore some common and useful React Hooks then look at the cool custom ones I found. This article serves as a prologue/overview of this series. Let's begin!

What are hooks?

image.png Hooks are available for React packages 16.8.0 or higher. In simple words, hooks are in-built functions that allow developers to use React features such its lifecycle methods, state, props in React functional components.

The naming convention of React Hooks is useSomething such as useState, useEffect, etc. In future articles of this series, you'll see how each of these hooks work and how to use them.

Important things to know

Calling React Hooks

The most important thing to note about Hooks is that they can't be used inside class components. They can only be called in a React function component. Other situations in where Hooks are forbidden to use:

  • Inside event handlers
  • Inside functions of other Hooks like useMemo, useReducer and useEffect
  • Inside regular JavaScript functions
function Bad1() {
  function handleClick() {
    // πŸ”΄ Bad: inside an event handler (to fix, move it outside!)
    const theme = useContext(ThemeContext);
  // ...

function Bad2() {
  const style = useMemo(() => {
    // πŸ”΄ Bad: inside useMemo (to fix, move it outside!)
    const theme = useContext(ThemeContext);
    return createStyle(theme);
  // ...

class Bad3 extends React.Component {
  render() {
    // πŸ”΄ Bad: inside a class component
    useEffect(() => {})
    // ...

Source: reactjs.org/warnings/invalid-hook-call-warn..

Must be called at the top level

When calling Hooks in function components, they must be called at the top level to ensure that they called in the same order at every render.

In other words, they:

  • Cannot be inside conditional statements
  • Cannot be in loops
  • Cannot be in functions

Because that would mean that they may or may not be executed in the same order every time the component renders.

The documentation here provides a detailed explanation on why this must be so.

All in All

In summary, learning React Hooks is not hard at all. As long as we follow its rules and understand how each of them works, we can easily use this amazing React feature in our projects.

Thanks for reading this simple introduction to Hooks. In the next article of this series, we shall take a look at our first Hook: useState. Stay tuned and cheers!

P.S. Happy Chinese New Year to any chinese readers! ζ–°εΉ΄εΏ«δΉοΌŒ ζ­ε–œε‘θ΄’οΌ


Did you find this article valuable?

Support Victoria Lo by becoming a sponsor. Any amount is appreciated!