
1. 초기 상태
import { useState, useEffect } from "react"; function App() { return ( <div> </div> ); } export default App;
2. 버튼 만들기
import { useState, useEffect } from "react"; function App() { const [showing, setShowing] = useState(false); const onClick = () => setShowing((prev) => !prev) return ( <div> <button onClick={onClick}>{showing ? "Hide" : "Show"}</button> </div> ); } export default App;


3. Hello 컴포넌트를 추가하기
import { useState, useEffect } from "react"; function Hello() { return <h1>Hello</h1>; } function App() { const [showing, setShowing] = useState(false); const onClick = () => setShowing((prev) => !prev) return ( <div> {showing ? <Hello /> : null} <button onClick={onClick}>{showing ? "Hide" : "Show"}</button> </div> ); } export default App;

- 클릭 이벤트에 따라 상태가 변경되고 그 상태에 따라 보이고 숨기기
import { useState, useEffect } from "react"; function Hello() { useEffect(() => console.log("im here") , []); return <h1>Hello</h1>; } function App() { const [showing, setShowing] = useState(false); const onClick = () => setShowing((prev) => !prev) return ( <div> {showing ? <Hello /> : null} <button onClick={onClick}>{showing ? "Hide" : "Show"}</button> </div> ); } export default App;


4. Cleanup
- React의
useEffect
훅에서 사용하는 개념
- 컴포넌트가 언마운트될 때나 특정 상태가 변경될 때 이전에 설정된 리소스를 정리하는 과정
- 언마운트: 컴포넌트가 DOM에서 제거되는 과정
- 이벤트 리스너, 구독 등을 설정한 후, 이러한 리소스를 해제하거나 초기화하기 위해 사용
- 생성되고 없어지는 순간을 알 수 있음
import { useState, useEffect } from "react"; function Hello() { function byFn() { console.log("bye"); } function hiFn() { console.log("created"); return byFn; } useEffect(hiFn, []); return <h1>Hello</h1>; } function App() { const [showing, setShowing] = useState(false); const onClick = () => setShowing((prev) => !prev); return ( <div> {showing ? <Hello /> : null} <button onClick={onClick}>{showing ? "Hide" : "Show"}</button> </div> ); } export default App;


- 하나의 함수로 적용하기
import { useState, useEffect } from "react"; function Hello() { useEffect(() => { console.log("hi :)"); return () => { console.log("bye :("); }; }, []); return <h1>Hello</h1>; } function App() { const [showing, setShowing] = useState(false); const onClick = () => setShowing((prev) => !prev); return ( <div> {showing ? <Hello /> : null} <button onClick={onClick}>{showing ? "Hide" : "Show"}</button> </div> ); } export default App;


Share article