import React from 'react';
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from 'recoil';
const textState = atom({
key: 'textState', // unique ID (with respect to other atoms/selectors)
default: '', // default value (aka initial value)
});
const charCountState = selector({
key: 'charCountState', // unique ID (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
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}</>;
}
function CharacterCounter() {
return (
<div>
<TextInput />
<CharacterCount />
</div>
);
}
function App() {
return (
<>
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
</>
);
}
export default App;
해당 화면을 구현하기 위한 코드이다.
useRecoilState
은 useState의 업그레이드 버전이라고 생각하자. 대신atom({ key:'key', default:'default' })
가 필요하다.
useRecoilValue
은 useRecoilState의 value만 가져오는 것은 말함
selector
는 atom에 있는 상태를 직접 가져와서 데이터를 편집하는 것을 말하는데, 밑의 코드 처럼 key와 get을 통해서 textState라는 atom의 값을 가져와서 바꾸는 식의 상태관리를 의미한다.const charCountState = selector({ key: 'charCountState', // unique ID (with respect to other atoms/selectors) get: ({get}) => { const text = get(textState); return text.length; }, });