Summary

In this lesson, you learned that:

  • A ref is made with useRef(null) and given to an element with ref={inputRef}. Once the element is on the page, React puts it into inputRef.current, so handlers and effects can call its methods, such as inputRef.current.focus().
  • A ref can keep any value from one render to the next, and changing ref.current doesn'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 use and 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 .js file.
  • useLocalStorage(key, initialValue) works like useState and remembers the value in localStorage. 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.

Start programming for free

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

Or sign up with:

Back

5/5

Next