'Using react-router with recoil

I have 'react-router-dom' and 'recoil' in same application.

What is a proper way to update recoil state within route?

const ItemRouter = ()=> { 

   const [selectedItemId, setSelectedItemId] = useRecoilState(itemIdSelected); 

   return ( 
      <Route
        key="items"
        path="/item/:itemId/edit"
        render={({ match }) => (

          // TODO: i want to save itemId to recoil state;  
          // const itemId = match.params.itemsId;
          // setSelectedItemId(itemId); 

          <ItemEditor whId={match.params.itemsId} />
        )}
      />
   )}


Solution 1:[1]

You could simply have a component that relies on useEffect to update the Recoil atom reflecting the route parameter. Then, other atoms/selectors can read that piece of state (potentially, the ItemEditor component doesn't even need to accept the itemId as a prop if all of its state is in Recoil)

const itemIdSelectedState = atom({
    key: 'itemIdSelectedState',
    default: null,
});

const ItemRoute = ({ itemId }) => {
    const setItemIdSelected = useSetRecoilState(itemIdSelectedState);
    useEffect(() => setItemIdSelected(itemId), [itemId]);

    return <ItemEditor whId={itemId} />;
};

const ItemRouter = () => (
    <Route
        key="items"
        path="/item/:itemId/edit"
        render={({ match }) => <ItemRoute itemId={match.params.itemId} />}
    />
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mz8i