Your Own Hook

In the Effects lesson, you made the favorites stay: a useState with a function that reads localStorage, and an effect that saves to it. Now the app has notes too, and they should stay as well. You could copy those lines into Notes.jsx and change the key. But React lets you do better: write the lines once, in a function of your own, and call it from both components.

A function like that is your own hook: a function whose name starts with use and which calls other hooks. Here's a small one. It keeps true or false and returns it along with a function that flips it:

import { useState } from "react";

export default function useToggle(initialValue) {
    const [on, setOn] = useState(initialValue);

    function toggle() {
        setOn((on) => !on);
    }

    return [on, toggle];
}

A component calls it as it calls useState: const [showInfo, toggleInfo] = useToggle(false);. The hook returns an array, so each component gives the two values its own names.

Two things to know:

  • A hook shares code, not state. Each component that calls useToggle gets its own on, just as each call of useState does. When one changes, the others don't.
  • A hook is plain JavaScript, with no JSX, so its file ends in .js: useToggle.js. You import it as you import a component: import useToggle from "./useToggle.js";

Your hook will be useLocalStorage(key, initialValue). It works like useState, but it remembers its value in localStorage under key. The file useLocalStorage.js is ready: for now, the hook only passes on what useState returns. Inside, it needs the same two parts as the favorites in the Effects lesson, with key in place of "favorites" and initialValue in place of []. The effect now uses key too, so its dependencies are [key, value].

Instructions

Finish the hook in useLocalStorage.js: give useState a function that returns the value saved under key, or initialValue when nothing is saved, and add an effect that saves value under key whenever it changes. Then use the hook in Lineup.jsx: import it with import useLocalStorage from "./useLocalStorage.js";, and write useLocalStorage("favorites", []) in place of useState([]). The stars now stay after Run.

Use the same hook in Notes.jsx for the notes, under the key notes and with "" at first. Write something and click Run: the notes are still there, and so are the stars.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

3/5

Next