Next.js Discord

Discord Forum

useEffect(), the value doubling every time when the page is revalidate

Unanswered
Mini Satin posted this in #help-forum
Open in Discord
Mini SatinOP
i'm using zustand for store. when the page is revalidate, 'totalProfit' doubling every time

page.tsx -->
const profit = 10
const {increment} = useProfit(state => state)
useEffect(() => {
   increment(profit)
}, [])


useProfit.tsx --->
type StoreProps = {
    totalProfit: number,
    increment: (profit: number) => void
}

export const useProfit = create<StoreProps>((set) => ({
    totalProfit: 0,
    increment: (profit) => set((state) => ({totalProfit: state.totalProfit + profit})),
}))

10 Replies

@Ray are you in dev mode?
Mini SatinOP
yes
@Mini Satin yes
react strict mode run useEffect twice in dev mode
Philippine Crocodile
Is there a reason why the increment function has to happen in a useEffect, instead of using an event to increment the value?
@Philippine Crocodile Is there a reason why the increment function has to happen in a useEffect, instead of using an event to increment the value?
Mini SatinOP
Yes. When it enters the portfolio section, I want to save the earnings from each coin to the 'useProfit' store. I'm using Tanstack's 'data-table', I don't know how else to export the data.
Philippine Crocodile
I don't think useEffect is a good solution to mutate your server state/data. Rather look at the mutations in tanstack/react-query or use a server action to mutate your data.
@Mini Satin Click to see attachment
Philippine Crocodile
I think I don't understand why you would want the profit to increment when you view/render the UI.
Philippine Crocodile
If there is a specific thing (action) that a user does that causes the profit to increment, then at that point you want to mutate the data.