Redux vs. Mobx, ์น์ดํ ๋
ผ์์์ ์๋กญ๊ฒ ๋ฑ์ฅํ Recoil.
Recoil์ ๋ฌด์์ผ๊น?
"A state management library for React"
import React from 'react'; import { RecoilRoot, atom, selector, useRecoilState, useRecoilValue, } from 'recoil'; ใ ค function App() { return ( <RecoilRoot> <CharacterCounter /> </RecoilRoot> ); }
Components that use recoil state need RecoilRoot
to appear somewhere in the parent tree.
Atom
const fontSizeState = atom({ key: 'fontSizeState', default: 14, });
Atoms are units of state. They're updateable and subscribable: when an atom is updated, each subscribed component is re-rendered with the new value. They can be created at runtime, too. Atoms can be used in place of React local component state. If the same atom is used from multiple components, all those components share their state.
useRecoilState
function FontButton() { const [fontSize, setFontSize] = useRecoilState(fontSizeState); ใ ค return ( <button onClick={() => setFontSize((size) => size + 1)} style={{fontSize}}> Click to Enlarge </button> ); }
To read and write an atom from a component, we use a hook called
useRecoilState
. It's just like React's useState, but now the state can be shared between components.
1. Atom์์ ํ์๋ ๋ฐ์ดํฐ ์กฐ๊ฐ
2. ๋ฐ์ดํฐ๋ฅผ ๋ฐํํ๋ ์์ํจ์
selector
const fontSizeLabelState = selector({ key: 'fontSizeLabelState', get: ({get}) => { const fontSize = get(fontSizeState); const unit = 'px'; ใ ค return `${fontSize}${unit}`; }, });
selector
๋ atom์ ์ํ์ ์์กดํ๋ ๋์ ์ธ ๋ฐ์ดํฐ๋ฅผ ์์ฑํฉ๋๋ค. selector์์๋ get ํจ์(ํ์ํญ๋ชฉ)๋ฅผ ํตํด atom ์ ๋ณด๋ค์ 1๊ฐ ์ด์ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค. ์ด๋ฅผ ํตํด atom์ ์กฐํฉํ์ฌ ๊ฐ๋จํ ์๋ก์ด ๋ฐ์ดํฐ๋ฅผ ์์ฑํ ์ ์์ต๋๋ค.
๋ฌผ๋ก atom์ ์ ๋ณด๊ฐ ๋ฐ๋๋ฉด ํด๋น atom์ ์์กดํ๋ selector๋ ์๋์ผ๋ก ๋ฆฌ๋๋๋ง์ด ๋ฉ๋๋ค. ๋ํ ํ๊ฐ ์ด์์ atom ์ ๋ณด๋ฅผ ์ ๋ฐ์ดํธ ํ๋๋ก set ํจ์(์ ํํญ๋ชฉ)๋ฅผ ๋ฐ์ ์ ์์ต๋๋ค.
[์ธ์ฉ_https://blog.woolta.com/categories/1/posts/209]
useRecoilValue
function FontButton() { const [fontSize, setFontSize] = useRecoilState(fontSizeState); const fontSizeLabel = useRecoilValue(fontSizeLabelState); ใ ค return ( <> <div>Current font size: {fontSizeLabel}</div> <button onClick={() => setFontSize(fontSize + 1)} style={{fontSize}}> Click to Enlarge </button> </> ); }
๊ตฌ๋ ํ๋ ๊ฐ๋ง ๋ฐํํ๋ ํจ์์ ๋๋ค. ๊ฐ์ update ํจ์๊ฐ ํ์์์ ๊ฒฝ์ฐ ์ฌ์ฉํฉ๋๋ค.
[์ฐธ๊ณ ]