본문으로 건너뛰기

레시피 보관함 — 목록 · 검색 · 더하기

리액트 목차 만들고 배포하기 레슨 53 / 61

목차

'Thinking in React' 레슨의 설계대로 레시피 보관함을 짓는 레슨입니다. 한 파일이던 컴포넌트를 파일로 나누고, 레시피 목록은 RecipesProvider의 reducer와 Context 둘로, 검색 글과 분류는 ListScreen의 state로 두어 검색 · 분류 · 즐겨찾기 · 더하기 · 지우기가 되고 새로 고쳐도 레시피가 남는 화면을 만듭니다.

이 단계 시작 파일은 Thinking in React 레슨 예제의 파일 둘입니다.

4단계 중 1단계. 1. 파일 나누기. 파일 열하나. 컴포넌트를 한 파일에 하나씩 나누고, 목록 state를 맡을 파일 셋과 새 폼을 더합니다. 가져다 쓰이는 쪽부터 만들면 가져올 파일이 늘 먼저 서 있습니다.

1파일 나누기 — 가져다 쓰이는 쪽부터

앞 레슨 App.jsx의 컴포넌트 다섯을 '컴포넌트를 파일로 나누기' 레슨처럼 한 파일에 하나씩 나누고, 목록 state를 맡을 파일 셋과 새 폼 RecipeForm.jsx를 더합니다.

파일든 것
recipesContexts.jsContext 둘
RecipesProvider.jsxreducer · 불러오기 · 저장 · provider
useRecipes.js꺼내 쓰는 훅 둘
RecipeCard.jsx카드 하나
RecipeList.jsx카드 목록
SearchBar.jsx검색 칸
CategoryFilter.jsx분류 단추
RecipeForm.jsx새 레시피 폼
ListScreen.jsx목록 화면
App.jsxprovider로 감싼 화면

표의 차례대로, 가져다 쓰이는 쪽부터 만들면 파일마다 가져올(import) 파일이 먼저 서 있습니다. App.jsx를 맨 끝에 바꾸기 전까지 화면은 앞 레슨 판 그대로입니다.

2RecipesProvider — 목록 state 한 곳

목록을 바꾸는 일은 셋이고, 'reducer로 모으기' 걸음대로 일마다 action 하나를 둡니다. 고치기 · 갈아 끼우기 action은 다음 레슨에서 더합니다.

일action보내는 곳
더하기{ type: 'added', recipe }ListScreen
지우기{ type: 'deleted', id }RecipeCard
별{ type: 'toggledFavorite', id }RecipeCard

별 갈래도 받은 레시피를 고치지 않고 새 객체를 만듭니다(flipFavorite — 'reducer와 Context로' 레슨 자주 틀리는 곳).

불러오기는 '저장하고 불러오기' 레슨의 처음 값 함수 그대로이고, useReducer에는 세 번째 인자로 넘깁니다.

src/RecipesProvider.jsx
  const [recipes, dispatch] =
    useReducer(
      recipesReducer,
      null,
      loadRecipes,
    );

세 번째 인자를 주면 처음 state는 loadRecipes(null)이 돌려준 값입니다(리액트 문서 — 'the initial state is set to the result of calling init(initialArg).'). 받는 값은 쓰지 않아 둘째 인자는 null이고, 키 'recipe-box:recipes'가 없으면 씨앗 넷을, 있으면 JSON.parse한 목록을 돌려줍니다. 저장은 '저장하고 불러오기' 레슨의 저장 effect 그대로라, 어느 action이든 커밋 뒤에 새 목록을 씁니다.

받는 쪽은 Context 둘('reducer와 Context로' 레슨 3절)을 useRecipes.js의 훅으로 꺼냅니다.

src/useRecipes.js
export function useRecipes() {
  const recipes = useContext(
    RecipesContext,
  );
  …
  return recipes;
}

useRecipes()는 목록 배열을, useRecipesDispatch()는 dispatch 함수를 그대로 돌려줍니다('커스텀 훅으로 빼기' 걸음 3). 그래서 늘 const recipes = useRecipes();⁠처럼 이름 하나에 받고, 이 모양은 단원 끝까지 그대로입니다. …로 줄인 곳은 recipes가 null이면(provider 밖) 오류를 던집니다. 훅을 부르는 컴포넌트를 RecipesProvider 없이 그리면 쪽이 하얗게 비고, 빨간 줄에 그 글 'useRecipes는 RecipesProvider 안에서만 쓸 수 있습니다.'가 찍힙니다.

3ListScreen — 검색 글 · 분류와 보이는 목록

ListScreen은 'Thinking in React' 레슨 4절 표대로 검색 글 query와 고른 분류 picked를 제 state로 듭니다. 맞혀 봅니다. 처음 화면(씨앗 넷)에서, 검색 칸에 파스타를 친 채로, 폼에서 크림 파스타(양식 · 20분)를 더하면 목록은 어떻게 될까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 토마토 파스타 한 장 그대로
  • ② 토마토 파스타와 크림 파스타 두 장
  • ③ 다섯 장 모두 — 검색 칸이 비워진다
결과 보기

②입니다. 더하기는 dispatch로 목록 state만 바꿉니다. 목록이 바뀌면 그 Context를 읽는 ListScreen이 다시 렌더합니다. 검색 글은 ListScreen의 state라 '파스타' 그대로이고, 보이는 목록은 렌더할 때마다 지금 목록에서 다시 거르는 계산한 값이라('Thinking in React' 레슨 3절) 크림 파스타도 남습니다.

예상과 다르면 그곳이 배울 곳입니다. ①을 골랐다면 보이는 목록을 검색할 때 한 번 만들어 둔 것으로 본 것입니다. 보이는 목록을 state로 두면 그렇게 되어, 더한 레시피가 보이지 않습니다. ③을 골랐다면 폼이 칸을 비울 때 검색 칸도 비워진다고 본 것입니다. 폼이 비우는 것은 제 state title · minutes뿐입니다.

state 둘은 훅 둘 다음에 useState('') · useState('전체')로 만들고, 보이는 목록 visible은 그 아래에서 거릅니다.

src/ListScreen.jsx
  // 3. 가장 작은 state 찾기
  const visible = recipes
    .filter(
      (r) =>
        r.title.includes(query),
    )
    .filter(
      (r) =>
        picked === '전체' ||
        r.category === picked,
    );

글의 includes는 찾는 글이 들어 있으면 true라(JS '문자열 메서드'), 처음 검색 글 ''과 분류 '전체'에서는 넷 모두 보입니다. 밥을 치면 setQuery가 다음 렌더를 예약하고(리액트 규칙 3), 그 렌더에서 visible은 김치볶음밥 하나입니다.

위쪽 즐겨찾기 수는 recipes에서 세어 검색해도 그대로입니다.

4더하기 — 폼에서 dispatch까지

RecipeForm은 칸 글 셋(title · 폼의 picked · minutes)을 제 state로 듭니다. 분류는 고르는 칸(<select> — HTML:textarea-select-fieldset)이고, 다른 칸처럼 value · onChange로 잇습니다. 더하기를 누르면 받은 onSave를 부릅니다.

src/RecipeForm.jsx
  function handleSubmit(e) {
    e.preventDefault();
    const name = title.trim();
    if (name === '') return;
    onSave({
      id: crypto.randomUUID(),
      title: name,
      category: picked,
      minutes: Number(minutes),
      ingredients: [],
      favorite: false,
    });
    setTitle('');
    setMinutes('');
  }

crypto.randomUUID()는 브라우저가 주는 crypto의 함수로, 부를 때마다 무작위로 만든 36자 글을 돌려줍니다(MDN — 'A string containing a randomly generated, 36 character long v4 UUID.'). 씨앗 id도 'r1' 꼴 글이라, 수였던 할 일의 id와 다릅니다.

MDN은 이 함수를 'This feature is available only in secure contexts (HTTPS)'라고 적습니다. 보안 컨텍스트(secure context)는 https나 내 컴퓨터 주소(localhost)에서 받은 쪽이라, --host로 연 내부 주소(http://192.168.…)를 휴대폰에서 보면 함수가 없어 더하기에서 'crypto.randomUUID is not a function' 빨간 줄이 찍힙니다. 이 단원은 내 컴퓨터에서만 엽니다.

ListScreen의 handleSave는 받은 레시피를 added action에 실어 보내고, 카드 목록과 위쪽 수는 새 목록에서 다시 나옵니다.

예제

끝 파일 열하나입니다. recipes.js는 그대로이고, 새 파일 아홉은 접어 둡니다.

src/ 파일 열 보기 — 그대로 하나 · 새 파일 아홉

코드 주석의 번호는 틀마다 셉니다 — 2.는 'reducer로 모으기'의 걸음이고, 3. · 4. · 5.는 Thinking in React의 걸음입니다.

src/recipes.js — 앞 레슨 그대로입니다.

src/recipes.js
export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

export const initialRecipes = [
  {
    id: 'r1',
    title: '김치볶음밥',
    category: '한식',
    minutes: 15,
    ingredients: [
      '밥',
      '김치',
      '달걀',
    ],
    favorite: true,
  },
  {
    id: 'r2',
    title: '토마토 파스타',
    category: '양식',
    minutes: 25,
    ingredients: [
      '파스타',
      '토마토',
    ],
    favorite: false,
  },
  {
    id: 'r3',
    title: '계란말이',
    category: '한식',
    minutes: 10,
    ingredients: [
      '달걀',
      '파',
    ],
    favorite: false,
  },
  {
    id: 'r4',
    title: '바나나 팬케이크',
    category: '디저트',
    minutes: 20,
    ingredients: [
      '바나나',
      '밀가루',
      '우유',
    ],
    favorite: true,
  },
];

src/recipesContexts.js — Context 둘입니다. JSX가 없어 .js이고, 이름이 길어 export const 뒤에서 줄을 나눴습니다.

src/recipesContexts.js
import {
  createContext,
} from 'react';

export const RecipesContext =
  createContext(null);
export const
  RecipesDispatchContext =
    createContext(null);

src/RecipesProvider.jsx — reducer · 불러오기 · 저장 · provider입니다(2절). RecipesProvider만 내보내 npm run lint가 조용합니다('reducer와 Context로' 레슨 자주 틀리는 곳).

src/RecipesProvider.jsx
import {
  useEffect,
  useReducer,
} from 'react';
import {
  initialRecipes,
} from './recipes.js';
import {
  RecipesContext,
  RecipesDispatchContext,
} from './recipesContexts.js';

const KEY =
  'recipe-box:recipes';

function loadRecipes() {
  const raw = localStorage
    .getItem(KEY);
  if (raw === null) {
    return initialRecipes;
  }
  return JSON.parse(raw);
}

function flipFavorite(recipe) {
  return {
    ...recipe,
    favorite: !recipe.favorite,
  };
}

// 2. action마다 새 state
function recipesReducer(
  recipes,
  action,
) {
  switch (action.type) {
    case 'added':
      return [
        ...recipes,
        action.recipe,
      ];
    case 'deleted':
      return recipes.filter(
        (r) =>
          r.id !== action.id,
      );
    case 'toggledFavorite':
      return recipes.map(
        (r) =>
          r.id === action.id
            ? flipFavorite(r)
            : r,
      );
    default:
      throw new Error(
        '모르는 action: ' +
          action.type,
      );
  }
}

function RecipesProvider({
  children,
}) {
  const [recipes, dispatch] =
    useReducer(
      recipesReducer,
      null,
      loadRecipes,
    );
  useEffect(() => {
    localStorage.setItem(
      KEY,
      JSON.stringify(recipes),
    );
  }, [recipes]);
  return (
    <RecipesContext
      value={recipes}
    >
      <RecipesDispatchContext
        value={dispatch}
      >
        {children}
      </RecipesDispatchContext>
    </RecipesContext>
  );
}

export default RecipesProvider;

src/useRecipes.js — 꺼내 쓰는 훅 둘입니다. JSX가 없어 .js이고, 이름 붙인 export라 쓰는 쪽이 중괄호로 가져옵니다('컴포넌트를 파일로 나누기' 레슨 3절).

src/useRecipes.js
import {
  useContext,
} from 'react';
import {
  RecipesContext,
  RecipesDispatchContext,
} from './recipesContexts.js';

export function useRecipes() {
  const recipes = useContext(
    RecipesContext,
  );
  if (recipes === null) {
    throw new Error(
      'useRecipes는 ' +
        'RecipesProvider ' +
        '안에서만 쓸 수 있습니다.',
    );
  }
  return recipes;
}

export function
  useRecipesDispatch() {
  const dispatch = useContext(
    RecipesDispatchContext,
  );
  if (dispatch === null) {
    throw new Error(
      'useRecipesDispatch는 ' +
        'RecipesProvider ' +
        '안에서만 쓸 수 있습니다.',
    );
  }
  return dispatch;
}

src/RecipeCard.jsx — 별과 '지우기'가 dispatch로 action을 보냅니다.

src/RecipeCard.jsx
import {
  useRecipesDispatch,
} from './useRecipes.js';

function RecipeCard({
  recipe,
}) {
  const dispatch =
    useRecipesDispatch();
  const star = recipe.favorite
    ? '★'
    : '☆';
  // 5. 바꾸는 일은 위로 알리기
  function handleStar() {
    dispatch({
      type: 'toggledFavorite',
      id: recipe.id,
    });
  }
  function handleDelete() {
    dispatch({
      type: 'deleted',
      id: recipe.id,
    });
  }
  return (
    <li>
      <h3>{recipe.title}</h3>
      <p>{recipe.category}</p>
      <p>{recipe.minutes}분</p>
      <button
        onClick={handleStar}
      >
        {star}
      </button>
      <button
        onClick={handleDelete}
      >
        지우기
      </button>
    </li>
  );
}

export default RecipeCard;

src/RecipeList.jsx — 받은 recipes를 카드로 그립니다. ListScreen은 거른 visible을 이 이름으로 넘깁니다.

src/RecipeList.jsx
import RecipeCard from
  './RecipeCard.jsx';

function RecipeList({
  recipes,
}) {
  return (
    <ul>
      {recipes.map((r) => (
        <RecipeCard
          key={r.id}
          recipe={r}
        />
      ))}
    </ul>
  );
}

export default RecipeList;

src/SearchBar.jsx — 받은 query를 칸에 보이고, 칠 때마다 onQueryChange로 알립니다.

src/SearchBar.jsx
function SearchBar({
  query,
  onQueryChange,
}) {
  return (
    <input
      placeholder="검색"
      value={query}
      onChange={(e) =>
        onQueryChange(
          e.target.value,
        )
      }
    />
  );
}

export default SearchBar;

src/CategoryFilter.jsx — '전체'와 분류 다섯을 단추로 그립니다. '거르기와 남은 수' 레슨의 필터 단추처럼 고른 단추에만 active가 붙습니다.

src/CategoryFilter.jsx
import {
  categories,
} from './recipes.js';

const choices = [
  '전체',
  ...categories,
];

function CategoryFilter({
  category,
  onCategoryChange,
}) {
  const buttons = choices.map(
    (c) => (
      <button
        key={c}
        className={
          c === category
            ? 'active'
            : ''
        }
        onClick={() =>
          onCategoryChange(c)
        }
      >
        {c}
      </button>
    ),
  );
  return <div>{buttons}</div>;
}

export default CategoryFilter;

src/RecipeForm.jsx — 칸 셋과 더하기입니다(4절). <option>에 value를 적지 않으면 태그 안의 글이 값입니다.

src/RecipeForm.jsx
import {
  useState,
} from 'react';
import {
  categories,
} from './recipes.js';

function RecipeForm({
  onSave,
}) {
  // 4. state 자리 정하기
  const [title, setTitle] =
    useState('');
  const [picked, setPicked] =
    useState(categories[0]);
  const [minutes, setMinutes] =
    useState('');
  function handleTitle(e) {
    setTitle(e.target.value);
  }
  function handlePick(e) {
    setPicked(e.target.value);
  }
  function handleMinutes(e) {
    setMinutes(e.target.value);
  }
  // 5. 바꾸는 일은 위로 알리기
  function handleSubmit(e) {
    e.preventDefault();
    const name = title.trim();
    if (name === '') return;
    onSave({
      id: crypto.randomUUID(),
      title: name,
      category: picked,
      minutes: Number(minutes),
      ingredients: [],
      favorite: false,
    });
    setTitle('');
    setMinutes('');
  }
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form
      onSubmit={handleSubmit}
    >
      <input
        placeholder="이름"
        value={title}
        onChange={handleTitle}
      />
      <select
        aria-label="분류"
        value={picked}
        onChange={handlePick}
      >
        {options}
      </select>
      <input
        type="number"
        placeholder="분"
        value={minutes}
        onChange={handleMinutes}
      />
      <button>더하기</button>
    </form>
  );
}

export default RecipeForm;

src/ListScreen.jsx — 훅 둘 · state 둘 · 보이는 목록(3절)과 handleSave(4절)입니다.

src/ListScreen.jsx
import {
  useState,
} from 'react';
import {
  useRecipes,
  useRecipesDispatch,
} from './useRecipes.js';
import SearchBar from
  './SearchBar.jsx';
import CategoryFilter from
  './CategoryFilter.jsx';
import RecipeList from
  './RecipeList.jsx';
import RecipeForm from
  './RecipeForm.jsx';

function ListScreen() {
  const recipes = useRecipes();
  const dispatch =
    useRecipesDispatch();
  // 4. state 자리 정하기
  const [query, setQuery] =
    useState('');
  const [picked, setPicked] =
    useState('전체');
  // 3. 가장 작은 state 찾기
  const visible = recipes
    .filter(
      (r) =>
        r.title.includes(query),
    )
    .filter(
      (r) =>
        picked === '전체' ||
        r.category === picked,
    );
  const favoriteCount =
    recipes.filter(
      (r) => r.favorite,
    ).length;
  // 5. 바꾸는 일은 위로 알리기
  function handleSave(recipe) {
    dispatch({
      type: 'added',
      recipe,
    });
  }

  return (
    <section>
      <SearchBar
        query={query}
        onQueryChange={setQuery}
      />
      <CategoryFilter
        category={picked}
        onCategoryChange={
          setPicked
        }
      />
      <p>
        즐겨찾기 {favoriteCount}개
      </p>
      <RecipeList
        recipes={visible}
      />
      <RecipeForm
        onSave={handleSave}
      />
    </section>
  );
}

export default ListScreen;

src/App.jsx는 두 조각이고, 둘 다 바뀌었습니다.

src/App.jsx
import RecipesProvider from
  './RecipesProvider.jsx';
import ListScreen from
  './ListScreen.jsx';

코드 아래 화면은 검색 칸에 파스타를 친 채로 크림 파스타(양식 · 20분)를 더하고 그 별을 누른 뒤 화면입니다. 화면 상자는 칸에 보이는 글을 value="…"로, 고른 분류를 selected=""로 적습니다 — Elements 판과 다를 수 있습니다. 찍어 둔 화면이라 눌러도 바뀌지 않습니다. 앞 코드에 이어 씁니다.

src/App.jsx
function App() {
  return (
    <RecipesProvider>
      <main>
        <h1>레시피 보관함</h1>
        <ListScreen />
      </main>
    </RecipesProvider>
  );
}

export default App;
<main><h1>레시피 보관함</h1><section><input placeholder="검색" value="파스타"><div><button class="active">전체</button><button class="">한식</button><button class="">양식</button><button class="">일식</button><button class="">중식</button><button class="">디저트</button></div><p>즐겨찾기 3개</p><ul><li><h3>토마토 파스타</h3><p>양식</p><p>25분</p><button>☆</button><button>지우기</button></li><li><h3>크림 파스타</h3><p>양식</p><p>20분</p><button>★</button><button>지우기</button></li></ul><form><input placeholder="이름" value=""><select aria-label="분류"><option>한식</option><option selected="">양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input placeholder="분" type="number" value=""><button>더하기</button></form></section></main>
결과 화면

검색 글은 파스타 그대로이고 더한 크림 파스타가 바로 보이며, 즐겨찾기는 3개입니다. 폼은 이름 · 분 칸만 비고 분류는 양식에 남습니다. 콘솔에 빨간 줄은 없습니다.

src/App.jsx 전체 보기
src/App.jsx
import RecipesProvider from
  './RecipesProvider.jsx';
import ListScreen from
  './ListScreen.jsx';

function App() {
  return (
    <RecipesProvider>
      <main>
        <h1>레시피 보관함</h1>
        <ListScreen />
      </main>
    </RecipesProvider>
  );
}

export default App;

다음 레슨이 이 파일 열하나에서 이어 갑니다.

자주 틀리는 곳

찾는 차례 ①~⑥으로 찾습니다. 둘 다 콘솔에 빨간 줄이 찍힙니다(①).

틀린 생각: 훅이 돌려준 목록도 props처럼 중괄호로 꺼낸다.

ListScreen에서 목록을 아래처럼 꺼내면 쪽이 하얗게 빕니다.

src/ListScreen.jsx
  const { recipes } =
    useRecipes();

돌려받은 배열에는 recipes 속성이 없어 꺼낸 값이 undefined이고, recipes.filter에서 렌더가 멈춥니다. 템플릿 린트는 조용합니다(해 보기 2).

맞는 규칙: 훅이 돌려주는 모양대로, 배열과 함수를 이름 하나에 받습니다(2절).

틀린 생각: 검색 칸은 <input>이니 value · onChange로 넘긴다.

src/ListScreen.jsx
      <SearchBar
        value={query}
        onChange={setQuery}
      />

SearchBar가 받는 query · onQueryChange가 비어, 친 글은 칸에 보이지만 목록은 그대로입니다. 칠 때마다 'onQueryChange is not a function' 빨간 줄이 찍히고, 핸들러에서 난 오류라 화면은 남습니다('이벤트' 레슨). RecipeForm에 onSubmit으로 넘기면 더하기에서 'onSave is not a function'이 찍힙니다. 린트는 둘 다 조용합니다.

맞는 규칙: props는 받는 쪽 중괄호 안의 이름으로 넘깁니다('Thinking in React' 레슨 5절 표).

확인 문제

1. 예제 끝 판에서 RecipeCard의 dispatch 두 줄을 아래로 바꿔 저장했습니다. 쪽을 새로 고친 뒤 토마토 파스타의 별을 누르면 어떻게 될까요?

src/RecipeCard.jsx
  const { dispatch } =
    useRecipesDispatch();
  • ① 쪽을 열자마자 화면이 하얗게 빈다
  • ② 별이 ★로 바뀐다
  • ③ 화면은 그대로이고, 콘솔에 Uncaught로 시작하는 빨간 줄이 찍힌다
정답

③입니다. useRecipesDispatch()는 dispatch 함수 그 자체를 돌려주고, 함수에는 dispatch라는 속성이 없어 꺼낸 값은 undefined입니다. 렌더에서는 이 값을 부르지 않아 화면이 뜹니다. 별을 누르면 handleStar 안의 dispatch(…)에서 멈춰 'dispatch is not a function' 빨간 줄이 찍히고, 별은 ☆ 그대로입니다.

  • ① 자주 틀리는 곳 첫째처럼 렌더가 멈춘다고 본 것입니다. 그곳은 렌더 중에 recipes.filter를 불렀고, 여기는 누를 때에야 dispatch를 부릅니다.
  • ② 중괄호로 꺼내도 같은 함수를 받는다고 본 것입니다. 중괄호는 받은 값의 속성을 꺼냅니다(JS '구조 분해로 꺼내기').

2. 처음 화면(씨앗 넷)에서 분류 단추 '한식'을 누르고, 검색 칸에 파스타를 칩니다. 목록에는 무엇이 보일까요?

  • ① 카드가 하나도 없다
  • ② 토마토 파스타 한 장
  • ③ 김치볶음밥과 계란말이 두 장
정답

①입니다. visible은 렌더할 때마다 두 filter를 차례로 거친 값입니다. 첫 filter가 토마토 파스타만 남기고, 둘째가 그 가운데 한식만 남기는데 토마토 파스타는 양식입니다. 위쪽 줄은 recipes에서 세어 즐겨찾기 2개 그대로입니다.

  • ② 검색이 고른 분류를 갈아 끼운다고 본 것입니다. picked는 '한식' 그대로라 둘째 filter가 계속 거릅니다.
  • ③ 분류를 고르면 검색 글이 걸리지 않는다고 본 것입니다. 첫 filter는 분류와 상관없이 늘 이름을 거릅니다.

3. 처음 화면(씨앗 넷)에서 계란말이의 '지우기'를 누르고, 검색 칸에 파스타를 친 뒤 쪽을 새로 고칩니다. 화면은 어떻게 될까요?

  • ① 씨앗 넷이 모두 보이고, 검색 칸은 빈다
  • ② 세 장이 보이고, 검색 칸은 빈다
  • ③ 토마토 파스타 한 장이 보이고, 검색 칸에 파스타가 남는다
정답

②입니다. 지운 뒤의 목록은 커밋 뒤 저장 effect가 recipe-box:recipes에 썼고, 새로 고치면 loadRecipes가 그 셋을 꺼냅니다. 검색 글은 ListScreen의 state라 저장되지 않고, 처음 값 ''부터라 셋이 모두 보입니다.

  • ① 새로 고치면 목록도 씨앗으로 돌아간다고 본 것입니다. 씨앗은 저장소에 키가 없을 때만 씁니다.
  • ③ 검색 글도 저장된다고 본 것입니다. 저장 effect가 쓰는 것은 recipes뿐입니다.

컴퓨터에서 해 보기(선택) — 점수에 들지 않습니다. 폰으로만 보고 있다면 건너뛰세요.

  1. 예제 끝 판으로 검색 · 분류 · 별 · 더하기 · 지우기를 해 보고, 쪽을 새로 고칩니다. 바꾼 목록은 남고 검색 칸은 빕니다. 개발 도구의 Application 판에서 Storage 아래 Local Storage를 펼치고, 개발 서버 주소를 골라 키 recipe-box:recipes와 값을 봅니다.
  2. src/ListScreen.jsx를 먼저 메모 앱에 옮겨 두고, 다 보면 되돌려 놓습니다. ListScreen 함수 맨 위의 const recipes = useRecipes(); 줄을 아래 두 줄로 바꿔 저장합니다.
src/ListScreen.jsx
  const { recipes } =
    useRecipes();
  1. 쪽을 새로 고친 뒤 봅니다. 화면이 하얗게 비고, 콘솔에 Uncaught TypeError:로 시작하는 빨간 줄 'Cannot read properties of undefined (reading 'filter')'와, 'An error occurred in the <ListScreen> component.'로 시작하는 노란 줄이 찍힙니다. 메모 앱에 옮겨 둔 판으로 되돌려 저장하고 쪽을 새로 고치면 화면이 돌아옵니다. 저장된 레시피는 그대로입니다.

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

리액트 목차로