1

I have to update an atom outside of an React Component (where I can't use hooks). What is the correct way to do this in order to get the updated value in my subscribing React Components with hooks like useRecoilState etc.?

user2779665
  • 21
  • 1
  • 3

1 Answers1

3

You generally don't want to run into this: I'd suggest to double check your approach first.

However, if you eventually still really need to update atoms outside of React Components you might give a try to Recoil Nexus.

In the same file where you have your RecoilRoot you'll have something like:

import React from 'react';
import { RecoilRoot } from "recoil"
import RecoilNexus from 'recoil-nexus'

export default function App() {
  return (
    <RecoilRoot>
      <RecoilNexus/>
      
      {/* ... */}
      
    </RecoilRoot>
  );
};


export default App;

Then where you need to read/update the values:

import yourAtom from './yourAtom'
import { getRecoil, setRecoil } from 'recoil-nexus'

Eventually you can get and set the values like this:


const loading = await getRecoil(loadingState)

setRecoil(loadingState, !loading)

That's it!


Check this CodeSandbox for a live example.

  • Thumbs up. Recoil Nexus is a great addition to recoil! – Michael Sep 11 '21 at 19:29
  • 1
    "You generally don't want to run into this" - do you mind explaining the "why" for that to someone new to recoil? Thank you in advance! – hannojg Sep 04 '22 at 12:33
  • @hannojg In a nutshell, you want to make sure to use Recoil native hooks whenever possible: you don't want to abuse this bridge. I have even seen in some projects `getRecoil` and `setRecoil` inside components - which is a completely unnecessary abstraction. – Luis Antonio Canettoli Ordoñez Sep 07 '22 at 10:22