git clone https://github.com/markcrispo/CSFS1010-Lab-3
cd CSFS1010-Lab-3
npm i
npm run dev
We'll continue building on the task tracker app that we started in Lab 2.
useMemo is a React hook that skips "expensive" operations on subsequent re-renders if the inputs to the operation haven't changed. This is a concept in computer science called memoization.
useMemo introduces some overhead, so you wouldn't want to use this hook everywhere. From the docs:
In general, unless you’re creating or looping over thousands of objects, it’s probably not expensive.
useMemowon’t make the first render faster. It only helps you skip unnecessary work on updates.
A product manager suggested a UX improvement:
When you add a a new task, you currently need to waste an extra click to focus the input before you start typing.
Tasks:
- When you add a new task or edit an existing task, the input should be focused automatically.
- The input can be focused with a combination of useRef, useEffect, and HTMLElement:focus()
In order to personalize the task tracker, we'll simulate logging in and changing users.
- In
App.jsx, add a Login button - On click, the user should be prompted with "What's your name?"
- For simplicity we'll use window.prompt()
- After signing in, the header should display "Username's Task Tracker" and the button should say "Change user"
Now the important part! We'll want to reset the Task Tracker whenever the username changes.
In this simple example, we could reset the state of ToDoList by lifting state to App.jsx, but that's not always practical. Instead, let's explore three alternative solutions:
- Add a
useEffectinToDoList.jsxthat resetstodoswheneverusernamechanges
- Add a
useStateinToDoList.jsxthat tracks the "previous" value ofusername, i.e. the value on the previous render - Reset
todoswheneverusername !== prevUsername - This is more performant than
useEffect, but is only allowed when a component is setting its own state.
- Add a
keyprop toToDoList.jsxto unmount and remount the component wheneverusernamechanges
The backend team has given you an endpoint to fetch a user's todos when they log in:
https://64dd28c2e64a8525a0f7af4a.mockapi.io/todos/:username
When a user logs in, make a GET request to the API above with the user's username.
If the user has to-dos saved, the endpoint will return status 200 and a JSON array of their todos state. The to-do list should be populated with their todos upon logging in.
Otherwise, the endpoint will return status 404 (not found), and the to-do list should display the current list of default to-dos.
For testing purposes, the following users have to-dos saved:
"mark"
"dave"
Hint: Here's how we made a network request in the lecture
const result = await fetch("https://64bc22537b33a35a4447124f.mockapi.io/cats")
const catsResult = await result.json()
setCats(catsResult)