인프런 커뮤니티 질문&답변

blossom_mind님의 프로필 이미지

작성한 질문수

[2024] 한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지

10.2) useMemo와 연산 최적화

useMemo관련 질문드립니다

해결된 질문

24.08.13 03:01 작성

·

63

0

import React, { useCallback, useMemo } from "react";
import "../List.css";
import TodoItem from "./TodoItem";
import { useState } from "react";
const List = ({ todos, onUpdate, onDelete }) => {
  const [search, setSearch] = useState("");
  console.log(todos);

  const onChangeSearch = (e) => {
    setSearch(e.target.value);
  };
  const getFilteredData = () => {
    if (search === "") {
      return todos;
    } else {
      return todos.filter((todo) =>
        todo.content.toLowerCase().includes(search.toLowerCase())
      );
    }
  };
  const filteredTodos = getFilteredData();
  const getAnalyedData = () => {
    console.log("getAnalyedData");
    const totalCount = todos.length;
    const doneCount = todos.filter((todo) => todo.isDone).length;
    const notDoneCount = totalCount - doneCount;
    return {
      totalCount,
      doneCount,
      notDoneCount,
    };
  };

  const analyzedData = useMemo(() => {
    return getAnalyedData();
  }, [todos]);

  return (
    <div className="List">
      <div className="GetAnalyedData">
        <h1>total :::{analyzedData.totalCount}</h1>
        <h1>done :::{analyzedData.doneCount}</h1>
        <h1>notDone:::{analyzedData.notDoneCount}</h1>
      </div>

      <h4>검색어</h4>
      <input
        placeholder="검색어 입력"
        onChange={onChangeSearch}
        value={search}
      />

      <div className="todos_wrapper">
        {filteredTodos.map((todo) => {
          return (
            <TodoItem
              key={todo.id}
              {...todo}
              onUpdate={onUpdate}
              onDelete={onDelete}
            />
          );
        })}
      </div>
    </div>
  );
};

export default List;

 

  const getAnalyedData = () => {
    console.log("getAnalyedData");
    const totalCount = todos.length;
    const doneCount = todos.filter((todo) => todo.isDone).length;
    const notDoneCount = totalCount - doneCount;
    return {
      totalCount,
      doneCount,
      notDoneCount,
    };
  };

 

  const analyzedData = useMemo(() => {
    return getAnalyedData();
  }, [todos]);

이런식으로 넣어도 혹시 가능할까요 ???
Line 36:6: React Hook useMemo has a missing dependency: 'getAnalyedData'. Either include it or remove the dependency array react-hooks/exhaustive-deps
이런 에러가 떠서요 ..기능은 돌던데

답변 1

0

이정환 Winterlood님의 프로필 이미지
이정환 Winterlood
지식공유자

2024. 08. 14. 10:55

안녕하세요 이정환입니다.

네 문제 없습니다. 결론적으로 todos 데이터에 변화가 생겼을 때에만 동작시키게 되니까요 😃

추가로 Lint 경고 메세지는 강의중 안내드렸듯 무시하셔도 괜찮습니다!