| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 | 
| 12 | 13 | 14 | 15 | 16 | 17 | 18 | 
| 19 | 20 | 21 | 22 | 23 | 24 | 25 | 
| 26 | 27 | 28 | 29 | 30 | 31 | 
													Tags
													
											
												
												- map
- CORS
- MSA
- 투포인터
- tailwind
- 태그된 유니온
- 인터섹션
- ESlint
- async/await
- 공변성
- webpack
- dfs
- Jest
- recoil
- autosize
- app router
- React
- RTK Query
- 인증/인가
- 리터럴 타입
- 결정 알고리즘
- useAppDispatch
- 타입 좁히기
- SSR
- TS
- Promise
- 호이스팅
- 무한 스크롤
- CI/CD
- 반공변성
													Archives
													
											
												
												- Today
- Total
짧은코딩
최적화4-삭제, 수정 최적화 본문
반응형
    
    
    
  이전까지 한 최적화를 해도 모든 최적화가 되진 않는다.
특히 심각한 것은 댓글을 삭제하면 다른 댓글도 리렌더링된다.
-DiaryItem.js
import React, { useEffect, useRef, useState } from "react";
const DiaryItem = ({
  onEdit,
  onRemove,
  author,
  content,
  created_date,
  emotion,
  id,
}) => {
  useEffect(() => {
    console.log(`${id}번 째 아이템 렌더!`);
  });
  // isEdit가 false면 평소, true면 수정하는 상태
  const [isEdit, setIsEdit] = useState(false);
  const toggleIsEdit = () => setIsEdit(!isEdit);
  // 기본값 content로 해야 원래 값에서 수정 가능
  const [localContent, setLocalContent] = useState(content);
  const localContentInput = useRef();
  const handleRemove = () => {
    if (window.confirm(`${id}번째 일기를 정말 삭제하시겠습니까?`)) {
      onRemove(id);
    }
  };
  // 수정하다가 취소하고 다시 수정하면 처음에 취소한 그대로 있음
  const handleQuitEdit = () => {
    setIsEdit(false);
    setLocalContent(content);
  };
  const handleEdit = () => {
    if (localContent.length < 5) {
      localContentInput.current.focus();
      return;
    }
    if (window.confirm(`${id}번 째 일기를 수정하시겠습니까?`)) {
      onEdit(id, localContent);
      toggleIsEdit();
    }
  };
  return (
    <div className="DiaryItem">
      <div className="info">
        <span className="anuthor_info">
          작성자 : {author} | 감정점수 : {emotion}
        </span>
        <br />
        <span className="date">{new Date(created_date).toLocaleString()}</span>
      </div>
      <div className="content">
        {isEdit ? (
          <>
            <textarea
              ref={localContentInput}
              value={localContent}
              onChange={(e) => setLocalContent(e.target.value)}
            />
          </>
        ) : (
          <>{content}</>
        )}
      </div>
      {isEdit ? (
        <>
          <button onClick={handleQuitEdit}>수정 취소</button>
          <button onClick={handleEdit}>수정 완료</button>
        </>
      ) : (
        <>
          <button onClick={handleRemove}>삭제하기</button>
          <button onClick={toggleIsEdit}>수정하기</button>
        </>
      )}
    </div>
  );
};
export default React.memo(DiaryItem);
마찬가지로 React.memo를 하고 useEffect로 몇 번째 댓글이 렌더되었는지 알려준다.
-App.js
import { useCallback, useMemo, useEffect, useRef, useState } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";
const App = () => {
  const [data, setData] = useState([]);
  const dataId = useRef(0);
  const getData = async () => {
    const res = await fetch(
      "https://jsonplaceholder.typicode.com/comments"
    ).then((res) => res.json());
    const initData = res.slice(0, 20).map((it) => {
      return {
        author: it.email,
        content: it.body,
        emotion: Math.floor(Math.random() * 5) + 1,
        created_date: new Date().getTime(),
        id: dataId.current++,
      };
    });
    setData(initData);
  };
  useEffect(() => {
    getData();
  }, []);
  const onCreate = useCallback((author, content, emotion) => {
    const created_date = new Date().getTime();
    const newItem = {
      author,
      content,
      emotion,
      created_date,
      id: dataId.current,
    };
    dataId.current += 1;
    setData((data) => [newItem, ...data]);
  }, []);
  const onRemove = useCallback((targetId) => {
    setData((data) => data.filter((it) => it.id !== targetId));
  }, []);
  const onEdit = useCallback((targetId, newContent) => {
    setData((data) =>
      data.map((it) =>
        it.id === targetId ? { ...it, content: newContent } : it
      )
    );
  }, []);
  const getDiaryAnalysis = useMemo(() => {
    const goodCount = data.filter((it) => it.emotion >= 3).length;
    const badCount = data.length - goodCount;
    const goodRatio = (goodCount / data.length) * 100;
    return { goodCount, badCount, goodRatio };
  }, [data.length]);
  const { goodCount, badCount, goodRatio } = getDiaryAnalysis;
  return (
    <div className="App">
      <DiaryEditor onCreate={onCreate} />
      <div>전체 일기 : {data.length}</div>
      <div>기분 좋은 일기 개수 : {goodCount}</div>
      <div>기분 나쁜 일기 개수 : {badCount}</div>
      <div>기분 좋은 일기 비율 : {goodRatio}</div>
      <DiaryList onEdit={onEdit} onRemove={onRemove} diaryList={data} />
    </div>
  );
};
export default App;그리고 App.js에서 onRemove, onEdit를 useCallback 함수를 이용해서 전 글에서 했던거처럼 수정한다. 
그러면 삭제, 수정, 새로운 글을 써도 렌더가 필요한 것만 된다.
반응형
    
    
    
  '인프런, 유데미 > 한입 크기로 잘라 먹는 리액트' 카테고리의 다른 글
| 컴포넌트 트리에 데이터 공급하기 (0) | 2022.06.01 | 
|---|---|
| 복잡한 상태 관리 로직 분리하기 (0) | 2022.05.30 | 
| 최적화3-컴포넌트 최적화 (0) | 2022.05.29 | 
| 최적화2-컴포넌트 재사용 (1) | 2022.05.28 | 
| 최적화 1 - useMemo (0) | 2022.05.27 | 
			  Comments
			
		
	
               
           
					
					
					
					
					
					
				 
								 
								