In 2029 React, one of the most popular JavaScript libraries, released version 16.8.0. In this version, React Hooks are available in a stable release.
During my time with Flatiron, I built my React project using an older version. So now, I will make sure to write the key changes and how they look for reference to whoever needs it!
Let’s start by making sure we understand hooks. “Hooks let you use state and other React features without writing a class”. A Hook is a special function that lets you “hook into” React features. The most common ones being ‘useState’ which lets you add React state to function components and ‘useEffect’ which tells React that your component needs to do something after render. We can always tell it is a hook because it is prefixed with ‘use’.
To start using these hooks:
- The hooks must execute in the same order they are defined
- Hooks cannot be inside of: if statements, loops, functions or nested.
-
We first destructure by putting the hooks we will need when importing React.
import React, { useState } from ‘react’;
The hook will return an array of two values: [ the state, a function that allows us to update the state]
-
We then call the hook and in the case of useState, we pass in the default state.
const [ count, setCount ] = useState(0)
“The useState hook returns a pair: the current state value and a function that lets you update it. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together.”
function Example() {
const [count, setCount] = useState(0);
}
Using classes it would look like:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
“The useEffect hook, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes.”
To compare:
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
}
Using classes it would look like:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`; } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`;
}
You can also create your own Hooks to reuse stateful behavior between different components, which you can learn more about HERE.
If you want to learn more in-depth about hooks and their possibilities here are the resources I used:
Top comments (0)