How to set initial value which is from custom hook in recoil?

898 Views Asked by At

In react, I can set initial value for useState by using request response, custom hook returns or something else, just like this:

function App() {
  const value = useCustomHook();
  const [state, setState] = useState(value);
};

And then I can use this state everywhere by using useContext.

Now I want to migrate to recoil from useContext, but I cannot find a way to set initial value which is from a custom hook.

The atomFamily seems to handle with this scenario, but I think it doesn't make sence to set value on every useRecoilState:

function Foo() {
  const value = useCustomHook();
  const [state, setState] = useRecoilState(valueState(value));

  return <Boo />
};

function Boo() {
  const state = useRecoilValue(valueState); // I want to use value in this way
}

Is it possible to set initial value once and use it everywhere in recoil?

useEffect can solve this problem, but I want to set initial value at once rendering, not twice.

const value = useCustomHook();
const [state, setState] = useRecoilState(valueState);

useEffect(() => {
  setState(value);
}, [value]);


  [1]: https://github.com/facebookexperimental/Recoil/issues/603
0

There are 0 best solutions below