React for JavaScript Programmers V: Beyond Props and State, or why React Hooks?

Previously we had discussed props (for child components) and states (for almost all components). Now, we will be discussing hooks, an alternative to state and props.

Previously, we have stated that functions cannot have states, and you need to rewrite them into classes to add state to them. With React Hooks, that is no longer true. For example:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

The bolded line is the important line... it declares 2 functions, one to "read" the count (count), and one to "set" the count (setCount), and they are both linked to the state "hook" useState, and count was initialized to 0 with useState(0).

SIDENOTE: These are related to, but not the same as "getters" and "setters".

There are obviously more than useState hook. Effect hook (useEffect) is linked to the component lifecycle and replaces some older lifecycle methods. In fact, you can write your own hooks. But that's an advanced topic.

So why use hooks? React's official stance is that you should NOT rewrite your existing code just to use Hooks. Instead, write NEW components with hooks, so they can work together.

And hooks allow you to jump over multiple levels of components (which state also does). But hooks work with functions, so you don't have to rewrite a function into a class to use state. 

If you *can* use hooks, do so. It will simplify your code. But if your existing code works fine, there is no need to mess with them.

Hooks also include simplification of context API through the useContext hook, but to discuss that, we need to discuss Context API itself first.


Comments

Popular posts from this blog

Yet another take on recursion

Problem Solving for Programmers: a Neglected Topic?

How to Solve a Problem, with Examples