1. 클래스 -> 함수 기본 구조
class MyComponent extends React.Component {
render () {
return <div>Hello</div>
}
}
function MyComponent {
return <div>Hello</div>
}
2. state -> useState
class Counter extends React.Component {
state = { count: 0 };
render() {
return (
<button
onClick={()=>{
this.setState({ count: this.state.count + 1 })
}}
>
{ this.state.count }
</button>
);
}
}
function Counter () {
const [count, setCount] = useState(0);
return (
<button onClick={()=>{ setCount(prev=>prev+1) }}>
{count}
</button>
);
}
3. 생명주기 -> useEffect
componentDidMount() {
console.log("mounted")
}
import { useEffect } from "react";
...
useEffect(()=>{
console.log("mounted")
},[])
4. props 사용
this.props.title
function MyComponent({ this }) {
return <h1>{title}</h1>
}
5. state가 아닌 변수 => useRef
class Chat extends React.Component {
socket = null;
componentDidMount() {
this.socket = new WebSocket(url);
}
}
import { useEffect, useRef } from "react";
function Chat() {
const socketRef = useRef(null);
useEffect(()=>{
socketRef.current = new WebSocket(url);
return ()=>{
socketRef.current?.close();
}
}, []);
return <div>Chat</div>
}