seunghyun Note
Recoil 본문
개인적으로 공부할 것들이 많은 react의 개념들을 정리해보려고 한다.
오늘은 recoil! 공식문서와 블로그를 참고했다.
https://recoiljs.org/ko/docs/introduction/getting-started
Recoil 시작하기 | Recoil
React 애플리케이션 생성하기
recoiljs.org
start Recoil
make react app
npx create-react-app my-app
install
npm install recoil
Recoil Root
- recoil상태를 사용하는 컴포넌트는 부모에
RecoilRoot
가 필요하다.
import React from "react";
import { RecoilRoot } from "recoil";
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from "recoil";
function App() {
return (
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
);
}
Atom
Atom
은 상태(state)의 일부를 나타낸다.Atoms
은 어떤 컴포넌트에서나 읽고 쓸 수 있다.Atom
의 값을 읽는 컴포넌트들은 암묵적으로atom
을 가져온다.Atom
을 부가설명을 해보면(이해하기가 어려웠음..) 초기에 상태관리가 필요한 모든 데이터를 설정해줘야한다.
//예시1) 이 코드는 아래의 코드블럭과 상관 없음 -> 단지 atom을 이해하기 위한 코드이다.
//state.js import {atom} from 'recoil';
export const valueState = atom({ key : 'value' //단순한 키값이지만 유니크한 값으로 설정하기
default : 0 // boolean, [], {} 등 설정이 가능하다.
})
//main.js
import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
import { valueState } from './state.js';
const [ value, setValue ] = useRecoilState(valueState) // 현재 상태 값과 상태 값을 업데이트 하는 2가지를 모두 사용
const value = useRecoilValue(valueState) // 현재 상태값만 사용
const setValue = useSetRecoilState(valueState) // 상태 값 업데이트하는 set값만 사용
- useState와는 다르게 어떤 컴포넌트든지 사용할 수 있다. (
Atom
에 변화가 생기면 그Atom
을 구독하는 모든 컴포넌트가 재렌더링 되는 결과가 발생한다) - 컴포넌트가
Atom
을 읽고 쓰게 하기 위해서는useRecoilState()
를 사용하면 된다.
function TextInput() {
const [text, setText] = useRecoilState(textState);
const onChange = (event) => {
setText(event.target.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange} />
<br />
Echo: {text}
</div>
);
}
useRecoilState()
: 현재 상태값과 상태 값을 업데이트 하는 2가지를 모두 사용한다.useRecoilValue()
: 현재 상태값만 사용useSetRecoilState
: 상태 값 업데이트하는 set값만 사용
Selector
Selector
는 파생된 상태(상태의 변화)의 일부를 나타낸다. 쉽게 말해서 기존에 선언한atom
을 전/후 처리하여 새로운 값을 리턴하거나 기존atom
의 값을 수정하는 역할을 한다.- 참조한
atom
의 값이 최신화되면 자동으로selector
의 값도 최신화가 되므로 관리하기에 좋다.
// ex2) selector를 이해해보자
//atom으로 기본적인 key를 설정한다.
export const sampleState = atom({
key: "sampleState",
default: 0,
});
//설정되어있는 `sampleState`를 selector를 사용해 값을 변경한다.
//
export const sampleSelector = selector({
key: "sampleSelector",
get: ({ get }) => get(sampleState) * 2,
set: ({ set }, newValue) => set(sampleState, newValue / 2),
});
- (다시 공식문서로 돌아오면...)
Selector
는 파생된 상태를 어떤 방법으로든 주어진 상태를 수정하는 순수 함수에 전달된 상태의 결과물로 생각할 수 있다.
const charCountState = selector({
key: "charCountState", // unique ID (with respect to other atoms/selectors)
get: ({ get }) => {
const text = get(textState);
return text.length;
},
});
useRecoilValue()
훅을 사용해서charContState
값을 읽을 수 있다.
CharacterCounter.js
import { atom, selector, useRecoilState, useRecoilValue } from "recoil";
//Atom은 상태의 일부
const textState = atom({
key: "textState",
default: "",
});
const charCountState = selector({
key: "charCountState",
get: ({ get }) => {
const text = get(textState);
return text.length;
},
});
export default function CharacterCounter() {
return (
<div>
<TextInput />
<CharacterCount />
</div>
);
}
function TextInput() {
const [text, setText] = useRecoilState(textState);
const onChange = (event) => {
setText(event.target.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange} />
<br />
Echo : {text}
</div>
);
}
function CharacterCount() {
const count = useRecoilValue(charCountState);
return <>Character Count : {count}</>;
}
728x90
'스터디 > REACT' 카테고리의 다른 글
Recoil & react-hook-from (✈️ travel list) (2) | 2024.03.13 |
---|---|
React-hook-form (2) | 2024.03.12 |
React 데이터 관리 및 라우팅 (1) | 2024.02.24 |