I have a React app that currently uses around fifty variables stored in the Context API. I would like to try using Recoil as an alternative but I have a question. Do I have to, and is it best practice to, store each variable in its own atom; and then import it individually each time I need to use it?
With Context I can just do:
const [appState, setAppState] = useState({
var1: "string",
var2: "string2",
var3: false,
var4: 23,
...
})
and then use appState and setAppState as the value in my Context provider. Defining and importing fifty individual atoms is a bit daunting. Granted I won't be using all fifty at the same time but it still seems a step back after using Context.
With Recoil I would have to:
export const var1 = atom({key: "var1", default: "string",})
export const var2 = atom({key: "var2", default: "string",})
etc...
and then:
import { var1, var2, var3, ... } from './RecoilAtoms'
Is there a better way to do this?
You can of course just save it in one atom:
const appState = atom({
key: 'appState',
default: {
var1: "string",
var2: "string2",
var3: false,
var4: 23,
// ...
}
})
I am not sure what you mean by "Is there a better way". My guess is, that you are referring to a monolithic solution, but the whole point of recoil is to split up your global monolithic state and just use it in an atomic fashion. Otherwise there is no real benefit in using recoil.
So yes, I would split it up in several atoms.