useSetRecoilState(state)

Returns a setter function for updating the value of writeable Recoil state.


function useSetRecoilState<T>(state: RecoilState<T>): SetterOrUpdater<T>;
type SetterOrUpdater<T> = (T | (T => T)) => void;
  • state: writeable Recoil state (an atom or a writeable selector)

Returns a setter function which can be used asynchronously to change the state. The setter may either be passed a new value or an updater function which receives the previous value as an argument.


This is the recommended hook to use when a component intends to write to state without reading it. If a component used the useRecoilState() hook to get the setter, it would also subscribe to updates and re-render when the atom or selector updated. Using useSetRecoilState() allows a component to set the value without re-rendering when the value changes.

Example

import {atom, useSetRecoilState} from 'recoil';
const namesState = atom({
key: 'namesState',
default: ['Ella', 'Chris', 'Paul'],
});
function NameInput() {
const [name, setName] = useState('');
const setNamesState = useSetRecoilState(namesState);
const addName = () => {
setNamesState(existingNames => [...existingNames, name]);
};
const onChange = (e) => {
setName(e.target.value);
};
return (
<>
<input type="text" value={name} onChange={onChange} />
<button onClick={addName}>Add Name</button>
</>
);
}