Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect() isn't getting called when the component is re-rendered. It only gets called once after a change in the file is made

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading