跳至主要內容

useRecoilState(state)

傳回一個二元組,其中第一個元素是 state 的值,第二個元素是一個設定項函數,在呼叫時會更新給定 state 的值。

此勾子會訂閱組件,以針對所要求 state 的任何變更重新進行呈現。

使用 useRecoilState_TRANSITION_SUPPORT_UNSTABLE() 以實驗性地支援基於轉換 Recoil 狀態的 React 18 轉換


function useRecoilState<T>(state: RecoilState<T>): [T, SetterOrUpdater<T>];

type SetterOrUpdater<T> = (T | (T => T)) => void;
  • state:一個 atom 或一個可寫入 selector。可寫入的選取器是其定義中同時具有 getset 的選取器,而唯讀選取器則只有一個 get

此 API 與 React useState() 勾子相似,但它取得的是 Recoil 狀態,而不是預設值作為參數。它會傳回一個二元組,其中包含 state 的目前值和一個設定項函數。設定項函數可能會將新值作為參數,或者將一個更新器函數作為參數,該函數接收前一個值作為參數。


當組件打算讀取和寫入狀態時,建議使用此 Hook。

在 React 組件中使用此 Hook 會讓此組件在更新狀態時重新渲染。此 Hook 可能會擲出例外狀況,如果狀態有錯誤或正等待非同步解決。請參閱本指南

範例

import {atom, selector, useRecoilState} from 'recoil';

const tempFahrenheit = atom({
key: 'tempFahrenheit',
default: 32,
});

const tempCelsius = selector({
key: 'tempCelsius',
get: ({get}) => ((get(tempFahrenheit) - 32) * 5) / 9,
set: ({set}, newValue) => set(tempFahrenheit, (newValue * 9) / 5 + 32),
});

function TempCelsius() {
const [tempF, setTempF] = useRecoilState(tempFahrenheit);
const [tempC, setTempC] = useRecoilState(tempCelsius);

const addTenCelsius = () => setTempC(tempC + 10);
const addTenFahrenheit = () => setTempF(tempF + 10);

return (
<div>
Temp (Celsius): {tempC}
<br />
Temp (Fahrenheit): {tempF}
<br />
<button onClick={addTenCelsius}>Add 10 Celsius</button>
<br />
<button onClick={addTenFahrenheit}>Add 10 Fahrenheit</button>
</div>
);
}