React's custom hooks allow developers to encapsulate and distribute code across components. In this article, we'll look at how to create and use custom hooks in a Next.js application, with an emphasis on managing state and logic as an example.
Custom hooks utilize the naming pattern useSomething and are functions that allow us to extract stateful logic from components. They enable code reuse, increase readability, and preserve a separation of responsibilities in React applications.
Setting Up the Next.js Project
npx create-next-app@latest .
To handle the status of a counter, let's create a new hook called useCounter. This hook will keep track of the counter's value and give functions to increase and decrease it.
// hooks/useCounter.js
import { useState } from 'react';
export const useCounter = (initialValue = 0) => {
const [count, setCount] = useState(initialValue);
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
const decrement = () => {
setCount((prevCount) => prevCount - 1);
};
return { count, increment, decrement };
};
Now, let's utilize the useCounter hook within a Next.js component to display the counter value and enable interaction.
import React from 'react';
import './style.css';
import { useCounter } from './hooks/useCounter';
export default function App() {
const { count, increment, decrement } = useCounter();
return (
<div className="container">
<h1>Counter Value: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
This example shows a straightforward Next.js application that makes use of a custom hook (useCounter) to control the counter's status. When the buttons are pressed, the counter value will either increase or decrease.
For the routing to operate properly, make sure both files (useCounter.js and index.js) are in the pages directory of your Next.js project.
Execute the following command to launch the Next.js application:
npm run dev
Navigate to http://localhost:3000 in your browser to interact with the counter and observe its functionality.
You can also use Stackblitz or any other online code editor you may like.
Here I am using the Stackblitz for convenience.
output:
This example shows how custom hooks may isolate functionality and state management within a Next.js application, enabling reusability and simpler component code. Feel free to build on this example or implement custom hooks into other functionality as needed for your project.