
mounting updating unmounting세가지로 나눠짐useEffect(setup, dependencies?)useEffect(setup);
//혹은
useEffect(setup, []); //
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();//serverUrl또는 roomId가 update될 때 실행, setup코드
return () => {
connection.disconnect(); //unmount될 때 실행 , cleanup 코드
};
}, [serverUrl, roomId]); //의존 배열
// ...
}
import { useState, useEffect } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setCount(c => c + 1); // ✅ Pass a state updater
}, 1000);
return () => clearInterval(intervalId);
}, []);
리액트 문서에 채팅예제가 잘 되어있는 것 같아서 나중에 참고하면 좋을 듯 합니당!
참고 : react.dev
코딩온 부트캠프 교안