CodeBlanks Logo Icon CodeBlanks

Summary - Custom hook basics

Write a useField hook for a form field and use it on two inputs.

Summary - Custom hook basics

In this group you learned what a custom hook is, its two rules, and the useToggle and usePrevious examples. Now you can write your own hooks.

The recipe: name with use prefix, call at the top level, use the hooks you need inside, and return a meaningful value. Naming and call-site rules keep React's hook order intact.

In the next step you'll write a page component using the useCounter hook.

Practice CounterPage with useCounter

Complete the skeleton. Write a CounterPage component. Call the useCounter hook and assign its result to increment. Show <button onClick={ '{ increment }' }>Increment</button>. Export it. (Assume useCounter is imported.)

Starter code

App.jsx
// Write the CounterPage component here

Sample solution

App.jsx
function CounterPage() {
  const increment = useCounter();
  return <button onClick={increment}>Increment</button>;
}

export default CounterPage;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which could be a custom hook name?

  • useFetch Correct answer
  • fetchData
  • GetUser
  • hook_user

Explanation: useFetch is a valid custom hook name.

2 Match the custom hook recipe

Term Meaning
use prefix Naming
top level Call
hooks inside Logic
return Value

All lessons in Intermediate