UseEffect
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/router";
export default function FunctionLifecycleRefPage() {
const router = useRouter();
const inputRef = useRef<HTMLInputElement>(null);
const [count, setCount] = useState(0);
// componentDidMount와 동일!!!
useEffect(() => {
console.log("마운트됨!!!");
inputRef.current?.focus();
// componentWillUnmount와 동일!!!
return () => {
console.log("여기서 나갈래요!!!");
};
}, []);
// componentDidUpdate와 비슷!!!
useEffect(() => {
console.log("수정되고 다시그려짐!!!!!");
}, [count]);
// useEffect의 잘못된 사용 예(1.추가리렌더링, 2.무한루프)
// useEffect(() => {
// setCount((prev) => prev + 1);
// }, [count]);
const onClickCounter = () => {
console.log(count);
setCount((prev) => prev + 1);
console.log("카운터를 클릭하셨습니다!!!");
};
const onClickMove = () => {
router.push("/");
};
console.log("나는 언제 실행되게?!"); // componentDidMount, useEffect와 비교하기
return (
<div>
<input type="text" ref={inputRef} />
<div>현재카운트: {count}</div>
<button onClick={onClickCounter}>카운트 올리기!!!</button>
<button onClick={onClickMove}>나가기</button>
</div>
);
}
마운트(화면에 첫 렌더링), 업데이트(다시 렌더링), 언마운트(화면에서 사라질 때) 특정 작업을 처리할 코드를 실행할 때 useEffect를 사용한다. 기본적으로 인자로 콜백함수(다른 함수의 인자로 전달된 함수)를 받는다.
useEffect에는 두 가지 모습을 보인다.
useEffect(( )=> { }), 렌더링 될 때마다 실행한다.
useEffect(( )=>{ },[ ]) 이 배열은 의존성배열이라고 불리는데 배열 안에 있는 값이 바뀔 때마다 실행한다. 빈 배열일 때는 첫 렌더링에서만 실행한다.
* 더 공부하기
https://ko.reactjs.org/docs/hooks-intro.html
Hook의 개요 – React
A JavaScript library for building user interfaces
ko.reactjs.org
https://ko.reactjs.org/docs/hooks-effect.html
Using the Effect Hook – React
A JavaScript library for building user interfaces
ko.reactjs.org
useRef
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/router";
export default function FunctionLifecycleRefPage() {
const router = useRouter();
const inputRef = useRef<HTMLInputElement>(null);
const [count, setCount] = useState(0);
// componentDidMount와 동일!!!
useEffect(() => {
console.log("마운트됨!!!");
inputRef.current?.focus();
// componentWillUnmount와 동일!!!
return () => {
console.log("여기서 나갈래요!!!");
};
}, []);
// componentDidUpdate와 비슷!!!
useEffect(() => {
console.log("수정되고 다시그려짐!!!!!");
}, [count]);
// useEffect의 잘못된 사용 예(1.추가리렌더링, 2.무한루프)
// useEffect(() => {
// setCount((prev) => prev + 1);
// }, [count]);
const onClickCounter = () => {
console.log(count);
setCount((prev) => prev + 1);
console.log("카운터를 클릭하셨습니다!!!");
};
const onClickMove = () => {
router.push("/");
};
console.log("나는 언제 실행되게?!"); // componentDidMount, useEffect와 비교하기
return (
<div>
<input type="text" ref={inputRef} />
<div>현재카운트: {count}</div>
<button onClick={onClickCounter}>카운트 올리기!!!</button>
<button onClick={onClickMove}>나가기</button>
</div>
);
}
const ref = useRef(value)
ref는 {current : value} 로 보여줌
useRef는 대표적으로 유용한 두 가지 상황이 있다.
첫 번째로, 저장공간으로 사용하게 된다.
State의 변화는 렌더링이 되면 컴포넌트 내부 변수들이 초기화된다.
Ref의 변화는 No렌더링이 되어 변수들의 값이 유지된다.
State의 변화로 렌더링되어도 Ref의 값은 유지된다. Ref는 렌더링이 되지 않기 때문에 성능이 좋아질 수 있다. 아무리 렌더링해도 값이 유지된다. 마운트된 시점에서 언마운트된 시점까지 유지된다. 렌더링이 되면 var같은 변수는 초기값으로 돌아가게 된다.
Ref를 통해 DOM 요소에 접근에 유용하다.
export default const App () => {
const inputRef = useRef();
useEffect(()=>{
input.Ref.current.focus();
},[])
const login = () => {
alert(`환영합니다. ${inputRef.current.value}`)
inputRef.current.focus();
}
retrun(
<div>
<input ref={inputRef} type="text" placeholder="username" />
<button onClick={login}>로그인</button>
</div>
);
};
inputRef를 console.log로 찍으면 current : input 이 객체로 받아와진다. 그래서 input.current.focus( )를 하면 인풋에 클릭이 되는 효과를 받을 수 있다.
https://ko.reactjs.org/docs/hooks-intro.html
Hook의 개요 – React
A JavaScript library for building user interfaces
ko.reactjs.org
https://ko.reactjs.org/docs/hooks-reference.html#useref
Hooks API Reference – React
A JavaScript library for building user interfaces
ko.reactjs.org
댓글