javascript / intermediate
Snippet
Encapsulating Logic with Custom Hooks
Custom hooks allow you to extract component logic into reusable functions, keeping your Next.js components clean and focused on UI.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { useState } from 'react';function useInput(initialValue) {const [value, setValue] = useState(initialValue);const onChange = (e) => setValue(e.target.value);return { value, onChange, reset: () => setValue('') };}// Usage in Next.js componentexport default function SignupForm() {const nameInput = useInput('');return <input type="text" {...nameInput} />;}
nextjs
Breakdown
1
function useInput(initialValue) {
Declares a custom hook that manages string input state.
2
{...nameInput}
Uses the spread operator to pass 'value' and 'onChange' props to the input element.