React Hooks
React Hooks were introduced with React 16.8.0 in 2018. Steven Spielberg's "Hook" was introduced in 1991. What do they have in common? Little to nothing, except for this vaguely Hook themed blog post!
Hooks allows developers to use React features without writing classes. With Hooks a functional component can have state!
State is a JavaScript object that stores information that is managed within the React component. - React Docs - State vs Props
So what is a Hook? A Hook is a special function that lets you “hook into” React features. - React Docs - What is a Hook?
Here is an example of a bare bones React class component followed by a React functional component that stores state using Hooks.
Class Component
import React, {Component} from 'react'
class ExampleReactClassComponent extends Component {
constructor() {
super()
this.state = {
exampleState: "Bangarang"
}
render() {
return ( <div>{this.state.exampleState}</div> )
}
}
Functional Component with Hooks
import React, { useState } from 'react'
function ExampleReactFunctionalComponent () {
const [exampleState, setExampleState] = useState("this is my state")
}
return ( <div>{exampleState}</div> )
Why Write Components Using Hooks?
Just take a look at the examples above - Hooks makes for cleaner, easier to read code. Hooks allow react developers to write components without creating a class every time. With Hooks you can use state and other react features in functional components. Now the "Stateless" functional component is only stateless if you want it to be.
This picture of Rufio from the 1991 smash hit "Hook" is super related to React Hooks.
There are some rules governing Hooks that you'll need to keep in mind. I've called out a couple from the React Docs below, but I recommend reading their full doc for more information.
Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions. Only call Hooks from React function components. React Docs - Hooks Rules
useState
In the functional component example above, the import statement read import React, { useState } from 'react'
. The React Hook useState
is how you can add state to a functional component.
useState
returns 2 values - the state value and a function that allows you to update state. You'll see useState
commonly written using destructuring like so:
const [bangarang, setBangarang] = useState("Bangarang!!!!")
Let's break the above statement down. We are setting two variables (the first variable is your state, the second is the function to update state) equal to the returned result of calling useState
with an argument. The variable names are arbitrary so choose your own banging variable names. The argument you enter with useState
is what you are initializing your state to. This can be anything (null, "RU-FI-O", whatever).
Below is an example of how to set and update state using the useState React Hook.
import React, { useState } from 'react'
function LostBoys() {
const [marbles, setMarbles] = useState("lost")
return (
<div>
<p>Marble status: {marbles}</p>
<button onClick={() => setMarbles("found")}>Look For Marbles</button>
</div>
)
}
This Gif of Lost Boy Tootles from the beloved 1991 blockbuster "Hook" is not a thinly veiled attempt at giving this blog post a theme.
useEffect
useEffect
runs after the component is rendered to the DOM. It is great for side effects that can be run asynchronously (like a fetch request!).
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. - React Docs - useEffect
useEffect
accepts an array as it's second argument. The array represents what useEffect
uses to decide when to fire. If you pass an empty array then useEffect
only fires after the first render.
import React, { useState, useEffect } from 'react'
function LostBoys() {
const [marbles, setMarbles] = useState(null)
useEffect(() => {
fetch('gofindmarbles') //pretend this is an API endpoint with lots of marble data
.then(response => response.json())
.then(marbleData => {
setMarbles(marbleData)
})
}, [])
return (
<div>
<p>Marble status: {marbles}</p>
</div>
)
Even More Hooks
I only covered the bare essentials for getting started with Hooks. Check out the React Docs for information about all of the available Hooks and how to create custom hooks.
One last note: Hooks are backwards compatible -- this means React applications can be written with both functional components using Hooks and class components
You are probably thinking to yourself, "Wow, this Hook theme thing really worked. It made sense, it was seamlessly woven with the subject matter." And you are right.
Resources Used:
Top comments (0)