Published on Mar 21, 2020 - 5 min read
This is a beginners guide to react hooks. It will take time to go through this guide, so grab a cup of coffee or whatever you like.
Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components. It does not work inside classes.
Don't worry though, classes aren't being removed or discouraged. React's Developers being given more ways to code!
There are couple of problem with Classes
React doesn’t offer a way to “attach” reusable behavior to a component. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.
The gist is classes can sometimes be confusing and can be written any number of ways. Dive into somebody else's project and you could be in for a world of different syntax and style choices. By allowing classes to be converted into smaller functional components, we can even further break out parts of our application into smaller and more focused components.
Hook state is the new way of declaring a state in React app. Hook uses useState() functional component for setting and retrieving state.
Let's say we have a component like this:
import React from 'react';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
This component will count the click on button.
With React Hooks, we are able to condense that class into this functional component:
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>
);
}
Notice how much easier the functional component would be for beginners just learning React.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
It declares a “state variable”. Our variable is called count but we could call it anything else, like state.
The only argument to the useState() Hook is the initial state. In Classes the state should be Object, but in Hooks it does not need to be Object. We can keep a number or a string if that’s all we need. In our example,0 is the initial state.
You might have noticed the square brackets when we declare a state variable:
const [count, setCount] = useState(0);
This JavaScript syntax is called “array destructuring”. It means that we’re making two new variables count and setCount, where count is set to the first value returned by useState, and setCount is the second.
useState gives us two variables and we can name our two variables whatever we want. Just know that:
The final part to useState is the argument that we pass to it. The useState argument is the initial state value. In the case of our counter, we started at 0.
We can even use useState() multiple times in the same function.
function ExampleWithManyStates() {
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
The Effect Hook lets you perform side effects in function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate() and componentWillUnmount() lifecycle methods.
Side-effects are things you want your application to make like:
Effects will run after every render, including the first render.
Let's compare a class to a functional component:
import React, { Component } from 'react';
class Example extends Component {
componentDidMount() {
console.log('this is componentDidMount!');
document.title = 'changeTitle';
}
render() {
return <div>stuff goes here</div>;
}
}
When using the the Effect Hook, we use useEffect()
function Example() {
useEffect(() => {
console.log('this is useEffect ');
document.title = 'changeTitle';
});
return <div>stuff goes here</div>;
}
Since useEffect() runs every time a component renders, how do we get it to only run once, on mount? The Effect Hook can take a second argument, an array. It will look through the array and only run the effect if one of those values has changed.
// only run on mount. pass an empty array
useEffect(() => {
// only runs once
}, []);
// only run if count changes
useEffect(
() => {
// run here if count changes
},
[count]
);
Now, you have some understanding of hooks and how they work. If you want to learn hooks in-depth, you should check the official docs by React's Developers.
There are intentionally no comments on my blog. If you found any errors in this article, please feel free to contact me
I'm Ravin Pandu, I document everything I learn and help thousands of people in learning new stuffs everyday. My site has no ads, sponsors, or bullshit. If you enjoy my content, please consider supporting what I do.
Subscribe and get my latest blog post in your inbox.