Exploring React Hooks: An Introduction and Detailed Explanation

Kevin Diesenberg
2 min readMay 23, 2023

--

React Hooks, introduced in React 16.8, are a powerful feature that allows you to use state and other React features without having to write a class component. Hooks let you ‘hook into’ React’s state and lifecycle features from function components, making your codebase simpler and easier to read.

What are Hooks?

React Hooks are functions that let you hook into state and lifecycle methods from function components. There are two main hooks that you’ll likely use often — useState and useEffect - but React provides many others that you can use as per your needs.

useState

The useState hook allows you to add React state to function components. It takes one argument which is the initial state, and returns an array with two elements: the current state value and a function that lets you update it.

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>
);
}

useEffect

The useEffect hook lets you perform side effects in function components. It's like componentDidMount, componentDidUpdate, and componentWillUnmount combined.

import React, { useState, useEffect } from 'react';

function Example() {
const [count, setCount] = useState(0);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
document.title = `You clicked ${count} times`;
});

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

Rules of Hooks

There are two main rules for using Hooks:

  1. Only Call Hooks at the Top Level: Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function.
  2. Only Call Hooks from React Functions: Don’t call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components or from custom Hooks.

Other Hooks

Besides useState and useEffect, React provides other hooks such as useContext, useReducer, useCallback, useMemo, useRef, and useImperativeHandle.

Conclusion

React Hooks offer a more intuitive way to handle state and side effects and greatly simplify your React code. They also make it easier to extract, test, and reuse stateful logic, and unify your component logic instead of spreading it over lifecycle methods.

In the next post, we’ll look at the comparison of React state management solutions, Redux vs. Context API. Until then, happy coding!

--

--

Kevin Diesenberg
Kevin Diesenberg

Written by Kevin Diesenberg

Software Engineer | JavaScript | React | Ruby | Rails | SQL | Skydiver | Outdoor Enthusiast | Paramotor Pilot | Cyclist | Edible Mushroom Hunter

No responses yet