사용교재 : 벨로퍼트와 함께하는 모던 리액트
범위 : 1.21 ~ 1.27
노션 용량문제로 Migration
필요한 기능을 하나의 함수로 만들어서 재활용 가능하게 만든 것
→ 범용적으로 사용할 수 있게 구조를 짜는게 중요할 듯
관례: 맨 앞에 use
를 붙여서 네이밍
function useInputs(initialForm) {
const [form, setForm] = useState(initialForm);
// change
const onChange = useCallback(e => {
const { name, value } = e.target;
setForm(form => ({ ...form, [name]: value }));
}, []);
const reset = useCallback(() => setForm(initialForm), [initialForm]);
return [form, onChange, reset];
}
export default useInputs;
// 사용
const [{ username, email }, onChange, reset] = useInputs({
username: '',
email: ''
});
프로젝트 안에서 전역적으로 사용할 수 있는 값을 관리 (꼭 상태일 필요는 없다)
React.createContext(기본값)
: Context 생성Provider
: Context의 값 지정useContext()
: 만든 UserDispatch Context를 조회하는 hook// App.js
export const UserDispatch = React.createContext(null);
const [state, dispatch] = userReducer(reducer, initialState);
<UserDispatch.Provider value={dispatch}> ... </UserDispatch.Provider>
// UserList.js
import { UserDispatch } from "./App";
const dispatch = useContext(UserDispatch);
return (
<button
onClick={() => {
dispatch({ type: 'REMOVE_USER', id: user.id });
}}
>
)
상태 업데이트 시 불변성 관리를 대신해주는 라이브러리
import produce from "immer";
const nextState = produce(state, draft => {
draft.number += 1;
});
// state : 수정하고 싶은 상태
// draft => {} : 상태 업데이트 함수
(!) 첫번째 파라미터state
생략 시, 변환값은 상태가 아닌 함수가 된다
const updater = produce(draft => {
draft.done = !draft.done;
});
class Hello extends Component {
constructor(props) {
super(props);
this.handleIncrease = this.handleIncrease.bind(this);
this.state = {
counter: 0
};
}
handleIncrease() {
console.log('increase', this);
}
render() {
const { color, name } = this.props;
return (
<div style={{ color }}>
안녕하세요 {name}
<button onClick={this.handleIncrease}>+1</button>
</div>
);
}
}
Hello.defaultProps = {
name: '이름없음'
};
export default Hello;
render()
: 필수! 렌더링하고 싶은 JSX
반환!
props
: this.props
로 조회
this
: 컴포넌트 인스턴스를 가리킬때 반드시 필요.
constructor
에서 bind
작업을 통해 연결super(props)
: 컴포넌트에 구현된 생성자 함수를 먼저 실행하겠다는 의미state
: 상태관리. constructor
에서 this.state
로 설정. 반드시 객체
this.setState()
. 함수형으로도 업데이트 가능setState
는 상태변경을 요청하는 함수로, 비동기적 업데이트가 된다. → 객체로 업데이트 요청을 보내면, 동일 내역이 여러번 요청되어도 한번만 수행된다.컴포넌트가 브라우저 상에서 나타나고, 업데이트 되고, 사라지게 될 때 호출되는 메서드들
constructor
getDerivedStateFromProps
props
로 받아온 것을 state
에 넣어 주고 싶을 때 사용render
componentDidMount
getDerivedStateFromProps
props
, state
가 바뀌었을 때 호출shouldComponentUpdate
render
getSnapshotBeforeUpdate
componentDidUpdate
함수에서 받아와서 사용가능componentDidUpdate
getSnapshotBeforeUpdate
에서 반환한 값을 조회 가능componentWillUnmount
setTimeout
등 제거에러체크 방법
props
값이 없을 때 조건문을 통해 null
을 렌더링function Users({ users }) {
if (!users) return null;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.username}</li>
))}
</ul>
);
}
componentDidCatch
사전에 예외처리하지 않은 에러가 발생했을 때, 에러를 잡아냄
componentDidCatch(error, info)
에러 체크 솔루션. componentDidCatch
로 잡아낸 에러 정보를 별도의 서버에서 수집하는 솔루션.
자동으로 코드 스타일을 관리해주는 도구. .prettierrc
에서 설정 관리
자바스크립트의 문법을 확인해주는 도구
에디터 내장 기능. 자주 사용되는 코드의 단축어를 만들어 코드 생성 빠르게.