ClassComponent
import { Component } from "react"; class ClassComp extends Component { state = { count: 0, }; setCount(num) { this.setState({ count: num, }); } render() { return ( <div> <button onClick={() => this.setCount(this.state.count + 1)}> + </button> <div>{this.state.count}</div> </div> ); } } export default ClassComp;
ClassComponent에서는 component에 선언한 state(상태값)나 props(속성값) 메서드를 참조하기 위헤 this 를 사용한다.
this로 참조 할 수 있는 프로퍼티
: state, props, refs, component method(이벤트 핸들링 시 예외 발생), recycle method
FucntionComponent
import { useState } from "react"; function FunctionComp() { const [count, setCount] = useState(0); const onClickAdd = () => { setCount(count + 1); }; return ( <div> <div>{count}</div> <button onClick={onClickAdd}> + </button> </div> ); } export default FunctionComp;
FunctionComponent에서는 useState Hook을 사용
데이터를 저장하는 방법
1. 서버(DB)에 저장
2. locaStorage(브라우저가 가지고 있는 임시 저장공간)에 저장 //브라우저 청소를 하지 않는 이상 사라지지 않는다.
3. Session Storage에 저장 : 브라우저를 종료하면 저장된 데이터가 사라지는 휘발성 저장공간
localStorage 사용하기
데이터 저장
localStorage.setItem(‘key’,’value’)
데이터 출력
localStorage.getItem(‘key’)
데이터 삭제
localStorage.removeItem(‘key’)
Context를 사용하면 데이터를 전역적으로 공유 가능하다. (부모 - 자식 - 손자) 컴포넌트에서 중간 다리 역할을 하는 자식 컴포넌트를 생략하고 손자 컴포넌트에서 props를 받아 사용 할 수 있다.
React Hook인 useContext는 이러한 Context를 좀 더 편하게 사용 할 수 있게 해준다.
createContext(initialValue)
- context 객체 생성
- createContext 함수 호출 시 provider와 consumer 컴포넌트 반환
- initialValue는 provider를 사용하지 않았을 때 적용될 초기값을 의미한다.
Context.Provider
- 생성한 context를 하위 컴포넌트에 전달하는 역할
Context.Consumer
- context의 변화를 감시하는 컴포넌트
- 설정한 상태를 불러올 때 사용