Skip to content

Commit

Permalink
React Hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Yoonyesol committed Jan 11, 2024
1 parent 7944c36 commit d0c0ac4
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 12 deletions.
14 changes: 2 additions & 12 deletions section3/vite-project/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import "./App.css";
import Controller from "./components/Controller";
import Viewer from "./components/Viewer";
import Even from "./components/Even";
import useUpdate from "./hooks/useUpdate";

//라이프사이클
//1. 마운트(탄생)
Expand All @@ -13,23 +14,12 @@ function App() {
const [count, setCount] = useState(0);
//상태변화 함수: 비동기적으로 동작

const isMountRef = useRef(false); //값을 저장하는 레퍼런스 객체로 useRef 사용

//1. 마운트
useEffect(() => {
console.log("마운트");
}, []);

//2. 업데이트(변화, 리렌더) 제어
//코드 업데이트 시점에만 실행되도록 하는 useEffect
useEffect(() => {
if (!isMountRef.current) {
//아래 코드의 가드 역할
isMountRef.current = true;
return; //아래 코드가 실행되지 않음
}
console.log("업데이트");
});
useUpdate(() => console.log("App 컴포넌트 업데이트")); //custom hook 사용

useEffect(() => {
console.log(count);
Expand Down
6 changes: 6 additions & 0 deletions section3/vite-project/src/components/Controller.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import useUpdate from "../hooks/useUpdate";

export default function Controller({ onClickButton }) {
useUpdate(() => {
console.log("Controller 컴포넌트 업데이트");
});

return (
<div>
<button onClick={() => onClickButton(-1)}>-1</button>
Expand Down
17 changes: 17 additions & 0 deletions section3/vite-project/src/hooks/useUpdate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useEffect, useRef } from "react";

export default function useUpdate(cb) {
const isMountRef = useRef(false); //값을 저장하는 레퍼런스 객체로 useRef 사용
//2. 업데이트(변화, 리렌더) 제어
//코드 업데이트 시점에만 실행되도록 하는 useEffect
useEffect(() => {
if (!isMountRef.current) {
//아래 코드의 가드 역할
isMountRef.current = true;
return; //아래 코드가 실행되지 않음
}
console.log("업데이트");

cb(); //매개변수로 받은 콜백함수 실행
});
}

0 comments on commit d0c0ac4

Please sign in to comment.