DrMaemi / blog

1 stars 0 forks source link

[React] Class to Functional 리팩토링 #175

Open DrMaemi opened 4 months ago

DrMaemi commented 4 months ago

가이드 (변경 순서)

  1. class 를 function으로 수정
    • class state, componentDid... 훅들 수정
    • constructor 제거
  2. render() 메서드를 return JSX 문으로 수정
  3. 모든 메서드를 function 형식으로 수정
    • state 훅 수정

Lifecycle

Class ```tsx componentDidMount() { console.log("Component did mount"); } componentDidUpdate() { console.log("Component did update"); } componentWillUnmount() { console.log("Component will unmount"); } ```
Functional ```tsx // componentDidMount() useEffect(() => { console.log('마운트 될 때'); }, []); // componentDidUpdate() useEffect(() => { console.log('state 값이 변할 때') }, [state]); useEffect(() => { console.log('렌더링 될 때'); }); // componentWillUnmount useEffect(() => { return () => { console.log('컴포넌트 제거될 때'); }; }, []); ``` ```tsx useEffect(() => { // 컴포넌트가 마운트될 때 실행되는 로직 fetchData(); connectSseEventSource(); // 컴포넌트가 언마운트될 때 실행되는 로직 return () => { evtSrc?.close(); }; }, []); ```

상세 case

A. 참조