Remembering What You Know

Run the code again, and everything you've marked is gone: state only lives while the app runs. To keep it, you need localStorage, and you already have a hook for that from the Refs and Custom Hooks lesson. It's in the file useLocalStorage.js:

export default function useLocalStorage(key, initialValue) {
    const [value, setValue] = useState(() => {
        const saved = localStorage.getItem(key);
        return saved === null ? initialValue : JSON.parse(saved);
    });

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    return [value, setValue];
}

You use it just like useState, and it returns the same pair: the value and the function that changes it. On top of that, it starts with what's saved under key, if anything is, and saves the value again whenever it changes. So one line is all you need to change: useState([]) becomes useLocalStorage("known", []). It's a hook, so it belongs at the top of App, with the other hooks.

Your own words should stay too. But don't save all of words: the app loads them from words.json every time it starts, and the effect would replace the saved ones anyway. Keep your own words in a state of their own instead, saved with useLocalStorage("ownWords", []), and put the deck together from both while rendering:

const deck = [...words, ...ownWords];

The deck isn't state, it's computed, like the score. It has to come after the check for null, because until the words arrive, ...words would end with an error. Below it, the card, the position, the score and handleNext() then work with deck instead of words.

Instructions

In App.jsx, import the hook (import useLocalStorage from "./useLocalStorage.js";) and create known with it: const [known, setKnown] = useLocalStorage("known", []);. Mark a word with I know it and run the code again: the score still counts it.

Keep your own words in const [ownWords, setOwnWords] = useLocalStorage("ownWords", []);, and let handleAdd() add the new word to the end of ownWords instead of words. Below the ifs, create deck as above, and use it instead of words in the rest of App. Add a word and run the code again: it's still in the deck.

Start programming for free

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

Or sign up with:

Back

6/8

Next