'understanding react hook useEffect inner working
i started working on a project using react as frontend framework, been a good journey, a lot a of doc and ready to use plugins. but i'm still trying to understand the different between these two pieces of code
import {useQuery} from "react-query";
import {GET_CURRENT_USER_QUERY} from "../sections/shared/user/requests/user-requests";
import {useContext, useEffect} from "react";
import {ClientContext} from "../contexts/RequestGraphqlClientContext";
// ----------------------------------------------------------------------
export default function MyAvatar({...other}: AvatarProps) {
const queryClient = useContext(ClientContext)
const [user, setUser] = useState(null)
if (!queryClient) {
throw new Error(`missing a UseGraphQLProvider`)
}
const {data, isLoading, isSuccess} = useQuery('me', () => {
return queryClient.request(GET_CURRENT_USER_QUERY)
})
useEffect(() => {
if (data && isSuccess) {
setUser(data.me)
}
}, [data, isSuccess])
and this one
import {useQuery} from "react-query";
import {GET_CURRENT_USER_QUERY} from "../sections/shared/user/requests/user-requests";
import {useContext, useEffect} from "react";
import {ClientContext} from "../contexts/RequestGraphqlClientContext";
// ----------------------------------------------------------------------
export default function MyAvatar({...other}: AvatarProps) {
const queryClient = useContext(ClientContext)
const [user, setUser] = useState(null)
if (!queryClient) {
throw new Error(`missing a UseGraphQLProvider`)
}
const {data, isLoading, isSuccess} = useQuery('me', () => {
return queryClient.request(GET_CURRENT_USER_QUERY)
})
if(data && isSuccess) {
setUser(data.me)
}
what i know is that useEffect is used to watch variable content change and trigger the effect, like computed property in vuejs ( coming from vue ). so what will be the different between making the user mutation inside a useEffect or just inside the function body ( called each time for each render ?)
Solution 1:[1]
One difference I can think of off the top of my head is that useEffect will only change if any of the variables it's dependent on changes, where the other condition will run the if block every time.
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 | jh316 |
