I was following a couple of tutorials about the usage of reactive variables as a state management solution in a react/apollo client app, and I noticed there 2 ways to reference the current value of a reactive variable:
- either by using the hook
useReactiveVar-const myVar = useReactiveVar(myReactiveVar); - or simply calling the reactive var without arguments
const myVar = myReactiveVar();
So my question is:
is there a benefit for using one way of referencing the reactive variable over the other and if so, then why?
I have a theory that the ways of referencing the current value of the reactive variable are similar to how setting state based on current state is used:
- We can either reference the state directly -
setState(count + 1);. - Or we pass a function -
setState((prev) => prev + 1). The second way is considered "safer" as it guarantees an accurate read of the current state during asynchronous code. I couldn't find out whether my theory is correct though!
This is a simple component where I use both ways and both are working in both instances where reading the current value of the reactive variable is used:
import React from 'react'
import { useQuery, useReactiveVar } from '@apollo/client';
import { missionsLimitRV } from '../../apollo/client';
import { GET_MISSIONS } from '../../data/queries';
export const Missions = () => {
const limit = useReactiveVar(missionsLimitRV); <---here--<<
const { data, loading } = useQuery(GET_MISSIONS, {
variables: {
limit: limit
}
});
const addMission = () => {
missionsLimitRV(missionsLimitRV() + 1) <---here-<<
}
if (loading) {
return <h2>Loading...</h2>
}
if (!data.missions.length) {
return <h2>No Missions Available</h2>
}
const missions = data.missions;
console.log(missions);
return (
<div>
<button onClick={addMission}>add mission</button>
{ missions.map((mission) => (
<div key={mission.id}>
<h2>{mission.name}</h2>
<ul>
{mission?.links?.map((link) => (
<li key={link}><a href={link}>{link}</a></li>
))}
</ul>
</div>
)) }
</div>
);
};
Thanks for reading! :)