Summary
In this lesson, you learned that:
- A ref is made with
useRef(null)and given to an element withref={inputRef}. Once the element is on the page, React puts it intoinputRef.current, so handlers and effects can call its methods, such asinputRef.current.focus(). - A ref can keep any value from one render to the next, and changing
ref.currentdoesn't render again. It's the place for things only your code needs, such as an interval's id. What the page shows belongs in state. - Your own hook is a function whose name starts with
useand which calls other hooks. It shares code between components, not state: each component that calls it gets its own. A hook without JSX goes in a.jsfile. useLocalStorage(key, initialValue)works likeuseStateand remembers the value inlocalStorage.useFetch(url)loads a file and returns{ data, loading, error }.- The rules of hooks: call them only at the top level of components and hooks, never in conditions, loops or handlers, and always in the same order. Return early only after all the hooks.
In the next lesson, Final Project, you'll put the whole course to work in a flashcard app for learning words, and you'll see how to make React apps on your own computer.
But first, a little practice: a festival ticket with your name, which the app remembers, and a button that puts the cursor into the name field. useLocalStorage.js is the hook you wrote, ready to use.
Instructions
Make the app remember the name: in place of useState, use useLocalStorage from useLocalStorage.js, under the key ticketName.
A click on Edit the name puts the cursor into the field: give the field a ref, and call its focus() in handleEdit.