React Hooks and Why You Should Use Them

Brock Byrd
Geek Culture
Published in
4 min readMar 11, 2021

What is a Hook and why would I use it? The React docs define a Hook as a special function that lets you “hook into” React features. Hooks are completely optional and don’t replace any React concepts, instead, they provide a more direct API to the React concepts such as props, state, context, refs, and lifecycle. Hooks are not only easier to work with and easier to test, they also make the code cleaner and clearer for the developer writing and the developer reading.

The two big Hooks to learn are the State hook and the Effect hook. The State hook allows you to add local state to a functional component. The Effect hook adds the ability to add “side effects” to a functional component; the side effects serve the same purpose as a classes lifecycle component but in a single API. Class components can become overwhelming with code and just seem too long for their purpose.

import React, { Component } from 'react';class Counter extends Component {constructor(props) {super(props);this.state = {count: 0}this.handleClick = this.handleClick.bind(this)}handleClick(e){e.preventDefault();this.setState({count: this.state.count + 1})}render() {return (<div><p>The count is: {this.state.count}</p><button onClick={this.handleClick}>Click me</button></div>)}}export default Counter;

This class component can now be written in a lot less lines of code by using Hooks making it easier to follow and more concise. The code above can be written in less lines of code and more compactly with Hooks below.

import React, { useState } from 'react';function Counter() {const [count, setCount] = useState(0)return (<div><p>The count is: {count} </p><button onClick={() => setCount(count + 1)}>Click me</button></div>)}export default Counter;

Using Hooks makes code and stateful logic reusable and a HUGE plus is that they don’t create another element in the DOM like Higher Order Components getting rid of the “wrapper hell” that can come with HOCs. Developers are aiming to have Hooks work better with future React optimizations by dead code elimination at compile time to increase performance. Less code for JavaScript to compile means less code to execute at runtime. That is why the Effect hook is probably the one Hook you should learn if nothing else.

The Effect hook doesn’t just combine duplicate code and speed up performance, it helps the developer avoid common bugs with lifecycle methods. The Hook helps a developer avoid using the componentDidUpdate lifecycle method improperly. UseEffect runs both after the first render and after every update by default. It always cleans up the previous effects before applying whatever effect comes next.

Although, “cleaning up” or applying an effect after every render could cause performance issues. The useEffect hook allows you to pass a second argument to compare whatever is passed from the previous render to the next render. If the items passed into the argument are the same between the next render and previous render, React would skip the effect saving some time and optimizing the code.

Custom Hooks are a great way to cut down on duplicate code and share logic between two JavaScript functions by creating a “third party” function. The React Docs define a custom Hook as a JavaScript function whose name starts with use and that may call other Hooks. The two popular ways to share stateful logic between components before were render props and HOCs. Hooks solve many of the problems that HOCs and render props do, but hooks don’t force you to add components to the “tree” and force you into wrapper or callback hell.

There are only a couple of unbreakable rules when it comes to using Hooks in an application.

  • ONLY CALL HOOKS AT THE TOP LEVEL

Don’t call Hooks from inide of conditions, nested functions, or loops. Following this rule will help ensure that your Hooks are called in the same order every render, which is what allows React to keep the state of Hooks between mulitple useState and useEffect calls. React relies on the order that the Hooks are called to know which state corresponds to which call.

  • ONLY CALL HOOKS FROM REACT FUNCTIONS

Don’t call Hooks from JavaScript functions, only call them from React function components and from custom Hooks. You will only be making your code more readable and easier to follow by having your stateful logic in a clear and visable source code.

If you find yourself having trouble with following these rules, React released an ESLint Plugin called eslint-plugin-react-hooks that forces the rules. The plugin is included by default into Create-React-App. If you have taken a different route of React creation, you can easily add the plugin by running npm install eslint-plugin-react-hooks — save-dev.

Hooks are not here to replace classes in React, they are merely an optional way of writing them and showing the true nature of React which is functional. Classes in React can make it easy to make mistakes and create bugs in your code, where Hooks aim to make it easier on the developer by not only creating solutions for these bugs, but making code more reusable. Hooks have no disadvantages when it comes to using multiple custom Hooks on a single component.

References

--

--

Brock Byrd
Geek Culture

Full Stack Software Engineer | Sports and Fitness