TL;DR: - In this article, we are going to go over React Hooks. This new feature is currently in the React 16.8 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!
React Hooks
React is constantly giving us cool new updates. Currently, in React 16.8, 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.
"React Hooks can make code more concise and gets rid of the need to use class components for state."
Tweet This
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.
Learn all about Hooks from our keynote (me and @sophiebits) and a deep dive by @ryanflorence! https://t.co/bGk9ajVtgi
— Dan Abramov (@danabramov) <a href="https://twitter.com/danabramov/status/1055863985298423808?ref_src=twsrc%5Etfw">October 26, 2018</a>
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.
"React Hooks are a way to 'hook' into a functional component."
Tweet This
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 react@16.8 react-dom@16.8
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.
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 ");
This is where our state is being set. The two values, phrase
and setPhrase
are placeholders. We also see a new feature, useState
.
phrase
is equal tothis.state
.setPhrase
is equal tothis.setState
.useState
is going to be our initial state value.
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". 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);
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" }]);
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>
);
}
The useEffect
hook replaces the following lifecycle methods:
componentDidMount
componentDidUpdate
componentWillUnMount
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.
About Auth0
Auth0 by Okta takes a modern approach to customer identity and enables organizations to provide secure access to any application, for any user. Auth0 is a highly customizable platform that is as simple as development teams want, and as flexible as they need. Safeguarding billions of login transactions each month, Auth0 delivers convenience, privacy, and security so customers can focus on innovation. For more information, visit https://auth0.com.
Conclusion
In conclusion, when using React Hooks, be sure to follow the docs
Class components are not going anywhere. Although, now we have this awesome, more concise way to write state in function components, rather than going between class and function.
Thanks for reading!