Home > Enterprise >  useEffect() isn't getting called when the component is re-rendered. It only gets called once af
useEffect() isn't getting called when the component is re-rendered. It only gets called once af

Time:12-18

the useEffect() part of the react component only gets called the first time the SingleStock component is rendered after I make a change in the file and save the file. I have no clue why this is happening.

import useAuthContext from "../hooks/useAuthContext" 
import StockDetails from "./StockDetails"
import TableHeader from "./TableHeader"
import useStocksContext from '../hooks/useStocksContext'
import { useEffect, useState } from "react"

const SingleStock = () => {

    console.log('SS RENDERED')

    const {user} = useAuthContext()
    const {stocks, dispatch} = useStocksContext()
    const [stock, setStock] = useState({})

    const id = window.location.pathname.split('/')[1]

    useEffect(() => {

        if (!user) {
            return
        }

        const fetchStock = async () => {
            const response = await fetch(`/api/stocks/${id}`, {
                headers: {
                    'Authorization': `Bearer ${user.token}`
                }
            })
            let json = await response.json()
            setStock(json)
        }

        console.log('hey there')

        if (user) {
            fetchStock()
        }
    }, [])

    console.log(stock)
    
    return (
        <div>
            <TableHeader/>
            {stock && <StockDetails 
                key={stock._id}
                stock={stock}
            />}
        </div>
    )
}

export default SingleStock

I know SingleStock is getting re-rendered because of my console.log statement at the top of the file. I know useEffect() isn't running because the state stock isn't getting set and "hey there" isn't getting logged to the console. I am stuck.

CodePudding user response:

There three cases for useEffect

1- if you want it to be executed in each render you should not specify the array of prop, like this:

useEffect(() => {
  //Runs on every render
});

2- if you want it to be executed just at the first render, same as componentDidMount, use it like this:

useEffect(() => {
  //Runs only on the first render
}, []);

3- if you want it to be executed depending on the change of a value or multiple values, use it like this:

useEffect(() => {
  //Runs on the first render
  //And any time any dependency value changes
}, [value1, value2]);

in your case I guess you need to use the first approach

  • Related