Overview of React Hooks

Overview of React Hooks

In this article, we are going to go over React Hooks. This new feature is currently in the alpha stage. With React Hooks, we will be able to write functional components that have a state; no need to use a class component for state anymore!

In this article, we are going to go over React Hooks. This new feature is currently in the alpha stage. With React Hooks, we will be able to write functional components that have a state; no need to use a class component for state anymore!

Learn what's new with React Hooks. For example, use state in a functional component.

Table of Contents

  1. React Hooks
  2. What Is a "Hook"?
  3. Using React Hooks in Projects
  4. What State Looks Like Currently
  5. What State Can Look Like With React Hooks
  6. Why the Square Brackets
  7. Multiple State Hooks
  8. The Effect Hook
  9. Conclusion

React Hooks

React is constantly giving us cool new updates. Currently, in React v16.8.0-alpha.1, we have React Hooks! What if I told you Hooks got rid of the major need for class components? This new feature may make your code more concise. Don’t we all want that?

But what is all the fuss with React Hooks? Why should I stop using class components? By all means, no need to stop using them. There is no plan to get rid of class components and if the developer wants to, the transition to switch to React Hooks is going to be seamless.

What Is a "Hook"?

React Hooks are a way to "hook" into a functional component. Functional components have never been able to hold a state, but with Hooks, it gives them the power to do so now.

If we were to head over to React docs on Hooks, they said it best with:

Hooks are an upcoming feature that lets you use state and other React features without writing a class. Source

State is written in a much cleaner way and setting or updating that state can be declared in as little as one line.

Then you have lifecycle methods like componentDidMount or componentDidUpdate that will be taken care of by useEffect. Hooks are powerful, and it allows for functional components to harness that power.

Using React Hooks in Projects

Now that we have a basic understanding of what React Hooks are, are we ready to use it in our projects? To get the current version of React into your project and start using React Hooks, simply run this command in your IDE:

npm install -S [email protected] [email protected] 

What State Looks Like Currently

In a class component, we are able to declare state and set that state with setState We are familiar with it looking something like this:

// 24 lines of code 

import React from "react"; 
import ReactDOM from "react-dom"; 

class ClassExample extends React.Component { 
  constructor(props) { 
    super(props); 
    this.state = { 
      phrase: "My Favorite Color Is " 
    }; 
  } 

render() { 
  return ( 
  <div> 
    <p>{this.state.phrase}</p> 
    <button onClick={() => this.setState({ phrase: this.state.phrase + "Blue" })}> Reveal the Color! 
    </button> 
  </div> 
  ); 
} 
} 

ReactDOM.render(<ClassExample />, document.getElementById("root")); 

The CodeSandbox for the above code can be found here.

In this example, we are declaring our state to be the phrase, "My Favorite Color Is ". We then create a button that when clicked, activates the setState and adds on the string, "Blue" to the phrase.

The output of this component would look like this:

And once the button is clicked, we should see this:

What State Can Look Like With React Hooks

If we took that same logic from the class component, put it into a functional component, and used React Hooks instead, we could cut out a lot of lines of code. Let’s see how that would look like.

// 17 lines of code 
import React, { useState } from "react"; 
import ReactDOM from "react-dom"; 

function HooksExample() { 
  const [phrase, setPhrase] = useState("My Favorite Color Is "); 

  return ( 
    <div> 
      <p>{phrase}</p> 
      <button onClick={() => setPhrase(phrase + "Blue")}> Reveal the Color! 
      </button> 
    </div> 
  ); 
} 
ReactDOM.render(<HooksExample />, document.getElementById("root"));

The CodeSandbox for the above code can be found here.

Hooks are an upcoming feature that lets you use state and other React features without writing a class. Source

We see here that state looks different, much different. Besides the keyword useState, we don’t even see state being used at all.

In this line:

const [phrase, setPhrase] = useState("My Favorite Color Is ");&nbsp;

This is where our state is being set. The two values, phrase and setPhrase are placeholders. We also see a new feature, useState.

  1. React Hooks
  2. What Is a "Hook"?
  3. Using React Hooks in Projects
  4. What State Looks Like Currently
  5. What State Can Look Like With React Hooks
  6. Why the Square Brackets
  7. Multiple State Hooks
  8. The Effect Hook
  9. About Auth0
  10. Conclusion

By using setPhrase within the React element being rendered, we are able to set a new state value and reveal the favorite color after the button is clicked.

The difference in the number of lines between these two examples is seven lines, but that can grow so much depending on your component. But the big difference is that we now can declare our state in a single line! We are able to replace our class constructor for a single function call.

By looking at useState a little more, this is the Hook that allows for the us to add in state to our functional component. You can read more about that in the React docs here!

Also, notice that in the Hooks example, it was a functional component. Using state in a functional component, who would have thought!

Why the Square Brackets?

This is using the JavaScript syntax, ["array destructuring"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment ""array destructuring""). Array destructing is when we are able to "unpack" values from an array and assign them to variables.

We are able to give the variables our own names, like phrase and setPhrase and then the useState knows that those two values are what it's going to be using. Once setting those two variables, the useState will be able to map over the values and know that the first value has the name of phrase and the second value has a name of setPhrase.

const [firstvalue, secondvalue] = useState(0);&nbsp;

Multiple State Hooks

Want to use more than just one state hook in a component? React allows for multiple state hooks in one component:

function LotsOfStates() { 
  const [name, setName] = useState("Sarah"); 
  const [color, setColor] = useState("Blue"); 
  const [shopping, setList] = useState([{ item: "Almond Milk" }]);&nbsp;

We are able to give different names to particular states, that way things are kept organized. Rather than using the word, state, we give it a name like, color or shopping so we know exactly which one we are working with.

The Effect Hook

Another neat feature of React Hooks is the use of useEffect. This will handle the lifecycle methods that we would want to use in our React code. The following code is based on an example presented in the React docs:

import { useState, useEffect } from 'react'; 

function Example() { 
  const [count, setCount] = useState(0); 

// Similar to componentDidMount and componentDidUpdate: 
useEffect(() => { 
  // Update the document title using the browser API 
  document.title = `You clicked ${count} times`; 
}); 

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

Source

The useEffect hook replaces the following lifecycle methods:

  1. React Hooks
  2. What Is a "Hook"?
  3. Using React Hooks in Projects
  4. What State Looks Like Currently
  5. What State Can Look Like With React Hooks
  6. Why the Square Brackets
  7. Multiple State Hooks
  8. The Effect Hook
  9. About Auth0
  10. Conclusion

In a sense, it combines the power of these three, and makes one mega lifecycle method!

The Effect Hook tells the component what we would like it to do at a certain time. After render, it will take care of any logic within the useEffect function. It could be something like the React docs example above or even to fetch data from an API.

reactjs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Mapbox GL Javascript wrapper for ReactJS

react-mapbox-wrapper Mapbox GL Javascript wrapper for ReactJS

JavaScript Expressions in JSX in ReactJs

Welcome, what is JSX Expressions in React Js in Hindi? JSX is an Expression Too After compilation, JSX expressions become regular JavaScript function calls a...

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.