Learn how React Hooks can revolutionize the way you write React applications and make your code more efficient and modular.
Hooks, a feature introduced in React 16.7, redefine how we write React apps. They provide a way to add state and lifecycle event handling to function components, making class components less necessary. Hooks also simplify event handling in function components.
Accessing State in Function Components
With the useState()
API, you can create state variables and modify them easily. The useState()
function accepts an initial value for the state item and returns an array containing the state variable and a function to modify the state. To access each individual item, array destructuring is used, like this: const [count, setCount] = useState(0)
.
Here’s an example:
import { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};
ReactDOM.render(<Counter />, document.getElementById('app'));
You can use multiple useState()
calls to create as many state variables as you need. Just make sure to call them at the top level of the component, not inside an if
statement or any other block.
Accessing Lifecycle Hooks
Another important feature of Hooks is access to lifecycle hooks in function components.
Using class components, you can register functions for componentDidMount
, componentWillUnmount
, and componentDidUpdate
events. These hooks are used for tasks like variable initialization, API calls, and cleanup.
Hooks provide the useEffect()
API, which accepts a function as an argument. This function is executed when the component is first rendered and on every subsequent re-render/update. React updates the DOM first and then calls the function passed to useEffect()
, ensuring a smooth UI rendering experience.
Here’s an example:
const { useEffect, useState } = React;
const CounterWithNameAndSideEffect = () => {
const [count, setCount] = useState(0);
const [name, setName] = useState('Flavio');
useEffect(() => {
console.log(`Hi ${name}, you clicked ${count} times`);
});
return (
<div>
<p>
Hi {name}, you clicked {count} times
</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
<button onClick={() => setName(name === 'Flavio' ? 'Roger' : 'Flavio')}>
Change name
</button>
</div>
);
};
ReactDOM.render(
<CounterWithNameAndSideEffect />,
document.getElementById('app')
);
To achieve the same functionality as componentWillUnmount
, simply return a function from the useEffect()
parameter:
useEffect(() => {
console.log(`Hi ${name}, you clicked ${count} times`);
return () => {
console.log(`Unmounted`);
}
});
You can use useEffect()
multiple times to separate unrelated logic. To improve performance, specify an array of state variables to watch. React will only re-run the effect if the items in this array change.
Similarly, you can specify an empty array to indicate that the effect should only run once, during mount time:
useEffect(() => {
console.log(`Component mounted`);
}, []);
useEffect()
is versatile and can be used for adding logs, accessing third-party APIs, and more.
Enabling Cross-Component Communication with Custom Hooks
One of the groundbreaking features of Hooks is the ability to write your own custom hooks. Custom hooks provide a way to share state and logic between components, reducing the need for render props and higher-order components.
To create a custom hook, simply define a function that starts with use
. It can accept any number of arguments and return any data.
Examples:
const useGetData() {
// ...
return data;
}
or
const useGetUser(username) {
// ...
const user = fetch(...);
const userData = ...;
return [user, userData];
}
In your components, you can use custom hooks like this:
const MyComponent = () => {
const data = useGetData();
const [user, userData] = useGetUser('flavio');
// ...
};
The decision to use hooks over regular functions depends on the specific use case and experience.
Tags: React Hooks, Function Components, State Management, Lifecycle Hooks, Custom Hooks