React Hooks Pt. I - useState

·

2 min read

What are hooks

Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions that "hook into" React state and lifecycle features from function components. It does not work inside classes.

In layman's terms, useState allows you to add state to function components.

Why use hooks

Prior to the introduction of hooks, we were using class comps with lifecycle methods and a class property called state. The lifecycle methods are as follows:

  • getInitialState(): executed before the creation of the component.
  • componentDidMount(): executed when the component gets rendered and placed on the DOM.
  • shouldComponentUpdate(): invoked when a component determines changes to the DOM and returns a “true” or “false” value based on certain conditions.
  • componentDidUpdate(): invoked immediately after rendering takes place.
  • componentWillUnmount(): invoked immediately before a component is destroyed and unmounted permanently.

If the above seems overwhelming, have no fear because hooks are here! Hooks were created to replace these methods which in turn makes working with React less complex and therefore easier to understand.

What is useState

useState is the newest way of declaring state in a React app. It utilizes array destructuring that takes in two values.

  let [name, setName] = useState('Pikachu');

The first value name is a new state variable that is initialized with the string Pikachu, and the second value setName is a function that changes the initial value when an event is fired.

import {useState} from "react";

const Pokemon = () => {
  let [name, setName] = useState('Pikachu');
  return (
    <>
      <p>{name}</p>
      <button onClick={() => setName('Raichu')}>Evolve pokemon</button>
    </>
  );
}

export default Pokemon;

In the above example, when the button is clicked, the setName function is executed to change name from Pikachu to Raichu. Give it a try!

When to use the useState hook

  • storing user input
  • store data from an API
  • state management
  • toggle flags

Rules of using useState

There are a few rules to follow when using the useState hook:

  • only call hooks from the top level
    • this means, hooks should be called from inside the function component at the very top before anything is returned
  • only call hooks from React functions
    • hooks cannot be called inside vanilla JavaScript, only React functions
    • hooks cannot be called inside of loops
    • hooks cannot be called after the return statement of the component

Debugging hooks

  • React developer tool (chrome plugin)
  • console.log
  • Debugger statement
  • Terminal

Also read: