RivoCode

React Essentials · Hooks · Lesson 12 of 26

Writing a Custom Hook

Concept

Writing a Custom Hook

A custom hook is just a function starting with use that packages up reusable stateful logic.

By the end of this lesson
  • Explain the core idea behind Writing a Custom Hook.
  • Predict output before running a change.
  • Test one realistic and one unusual input.
  • Use the result to make the next decision.
How to study this page
  1. 1. Read one concept.
  2. 2. Change the example.
  3. 3. Run, compare, and explain.
  4. 4. Complete the challenge below.
ExampleRunnable
function useToggle(initial = false) {
  const [value, setValue] = useState(initial);
  return [value, () => setValue((v) => !v)];
}
Try it Yourself »
Self-check before continuing

Without looking at the example, describe what changes when you modify one input in Writing a Custom Hook. Then reopen the editor and prove your explanation with a small test.

You are ready to continue when you can predict, test, and explain the result.

Your turn

Use the useToggle hook to build a show/hide password field.

Loading editor…

Console

Output will appear here...