Recoil Docs: Getting Started

dev_sang·2022년 6월 24일
0

React

목록 보기
1/1

Recoil Docs

Recoil is a state management library for React

Installation

npm install recoil

RecoilRoot

  • Components that use recoil state need RecoilRoot
  • RecoilRoot appears somewhere in the parent tree.
  • A good place to put this is in your root component:
import React from 'react';
import {
  RecoilRoot,
  atom,
  selector,
  useRecoilState,
  useRecoilValue,
} from 'recoil';

function App() {
  return (
    <RecoilRoot>
      <CharacterCounter />
    </RecoilRoot>
  );
}

Atom

  • An atom represents a piece of state.
  • Atoms can be read from and written to from any component.
  • Components that read the value of an atom are implicitly subscribed to that atom.
  • Any atom updates will result in a re-render of all components subscribed to that atom:
const textState = atom({
  key: 'textState', // unique ID (with respect to other atoms/selectors)
  default: '', // default value (aka initial value)
});
  • Components that need to read from and write to an atom
  • It should use useRecoilState() as shown below:
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>
  );
}

Selector

  • A selector represents a piece of derived state.
  • Derived state
    • transformation of state.
    • the output of passing state to a pure function that modifies the given state in some way:
const charCountState = selector({
  key: 'charCountState', // unique ID (with respect to other atoms/selectors)
  get: ({get}) => {
    const text = get(textState);

    return text.length;
  },
});

useRecoilValue() hook to read the value of charCountState

function CharacterCount() {
  const count = useRecoilValue(charCountState);

  return <>Character Count: {count}</>;
}
profile
There is no reason for not trying.

0개의 댓글