React Hooks — Everything You Need to Know
Michael Mitrakos
5 min read
React Hooks are the hot new thing to React, and they are very beneficial when you start to use them in your applications. Not only that…
React Hooks — Made Simple
Having worked across sites raking in over 50 billion website visits annually with Higglo Digital I write about tech topics and teach engineers to have solid foundations that will help them get ahead in their career. I also build awesome products for digital nomads — check it out!
JavaScript eBook
I’ve written an eBook on JavaScript that will take you from beginner to professional. Having been in your shoes moving to making over $200,000 per year in just a few years as a software engineer, I know exactly what it takes to get there. Check out the ebook now!
React Hooks are the hot new thing to React, and they are very beneficial when you start to use them in your applications. Not only that, but they’re very easy to understand and implement.
Why did we need React Hooks
What was wrong with the old way of doing things with lifecycle methods, and using the constructor to manage state?
- Using lifecycle hooks made React components very cumbersome and large. Often times your smart components would have two to four lifecycle methods which could add upwards of 40 or 50 lines per component. Using hooks will help you to reduce a portion of those lines to accomplish the same thing.
- The function setState is something i’m sure you’re very aware of. Although there was inherently nothing wrong with using setState and using the constructor to create state, the way React Hooks implements its replacement is (in my opinion) better because it’s declarative in specifying the specific pieces of state that you’re interacting with, and it reduces the amount of boilerplate code used in each component. We’ll dive more into this below!
So what really are hooks? React Hooks are built in functions that we can utilize to accomplish ‘lifecycle-like’ functionality and state management within a component. The two that you absolutely need to know are UseState and UseEffect. Let’s dive in:
useState
The useState function replaces the way we used to create state and set state in an old React component. That would look something like this:
class PrincessBrideComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
}
``` ``` `
`this.setState({ name: 'Inego Montoya' });`
}` ```
``` ` render() {
return (My name is {this.state.name}. You killed my father. Prepare to die.
);
}
}` ``` We’d create the structure of state within the class constructor, then throughout the component we would interact with state using `this.state` and `this.setState({ someProperty: someValue })` .
With hooks, instead of setting the entire state structure within the component’s constructor, we create it piece by piece like the below.
`import React, { useState, useEffect } from 'react';` ``` `function PrincessBrideComponent() {
**const [name, setName] = useState('');**` ``` // We can use the setName function to update name in state setName('Inigo Montoya');
}` return (
My name is {name}. You killed my father. Prepare to die.
);
}` ``` As you see, we create a property in state called `name` which is now a public variable in the component, and we also create a function called setName which we can use to interact with the `name` property. It’s as easy as that!
### useEffect
The useEffect function replaces lifecycle methods. Old React components would look something like this:
super(props);
this.state = {
}
``` ``` `
`this.setState({ name: 'Inego Montoya' });`
}` ```
``` `render() {
return (My name is {this.state.name}. You killed my father. Prepare to die.
);
}
}` ``` If we want to replace the above with React Hooks, it would look like this:
`import React, { useState, useEffect } from 'react';` ``` `function PrincessBrideComponent() {
const [name, setName] = useState('');` ``` **useEffect(() => {
setName('Inigo Montoya')
}, [])**` return (
My name is {name}. You killed my father. Prepare to die.
);
}` ``` So what is really happening in useEffect? You can visualize it as a function that runs 1) when the component is loaded, and 2) when any value in the array changes. In our case, we’ve got an empty array which means this function will only run once, ever.
Below is an example of a useEffect which will update every time the prop `name` changes.
`import React, { useState, useEffect } from 'react';` ```javascript
function PrincessBrideComponent({ name }) {
const [visibleName, setVisibleName] = useState('');` ```
// every time 'name' is a new value
`**useEffect(() => {`
setVisibleName(name)
}, [name])**
`return (
<div>
<h2>
My name is {visibleName}. You killed my father. Prepare to die.
</h2>
</div>
);
}` ```
#### Conclusion
React Hooks help us to reduce boilerplate code, and generally help us to be more declarative and functional in the way we write React code. If anything above is confusing or I can clarify in any way, please let me know! :)
I write often on many different programming topics. Let me know what else you’d like to learn!
#### JavaScript eBook
I’ve written an eBook on JavaScript that will take you from beginner to professional. Having been in your shoes moving to making over $200,000 per year in just a few years as a software engineer, I know exactly what it takes to get there. [Check out the ebook now](https://www.mitrakos.com/ebook)!
> I founded [Higglo Digital](https://higglo.io) and we can help your business crush the web game with an award-winning website and cutting-edge digital strategy. If you want to see a *beautifully designed website*, [check us out](https://higglo.io).> I also created [Wanderlust Extension](http://www.wanderlustapp.io/) to discover the most beautiful places across the world with highly curated content. Check it out!