The reason for the experienced behavior is not that useEffect isn't working. It's because of the way function components work.

If you look at your child component, if useEffect is executed and the component rerenders, defaultValues would be set to 0 again, because the code inside of the function is executed on each render cycle.

To work around that, you would need to use the useState to keep your local state consistent across renders.

This would look something like this:

function EditKat({ aa }) {
  // Data stored in useState is kept across render cycles
  let [defaultValues, setDefaultValues] = useState(0)

  useEffect(() => {
    setDefaultValues(2) // setDefaultValues will trigger a re-render
  }, [aa])

  console.log(defaultValues)
}
Answer from Linschlager on Stack Overflow
🌐
DhiWise
dhiwise.com › post › how-to-fix-useeffect-not-triggering-in-your-react-project
Reasons Why UseEffect Is Not Triggering In Your React App
May 29, 2024 - Sometimes developers encounter a situation where the useEffect not triggering as expected. This can be due to several reasons, such as an incorrect dependency array or the absence of dependencies that should trigger the effect.
🌐
GitHub
github.com › tannerlinsley › react-query › issues › 2628
Bug: useEffect not triggering on [deps] change · Issue #2628 · TanStack/query
September 2, 2021 - In card-status.js I registered useEffect which is watching for certain changes and it just displays the message whenever [deps] change. The problem is that one state change gets swallowed by useEffect. It can be seen if you click on a button and watch the console, useEffect is not triggered even though UI updates correctly aka rerender is triggered.
Author   Tosheen
🌐
GitHub
github.com › facebook › react › issues › 27256
Bug: useEffect not firing when depending on hook value · Issue #27256 · facebook/react
August 21, 2023 - React version: 18.2.0 Steps To Reproduce Setup a hook which returns a ref.current value. Setup a useEffect which depends on hooks return value. Have some useState which causes re-renders. The useEffect may not be called. Link to code exa...
Author   ThomasMorrison
🌐
freeCodeCamp
freecodecamp.org › news › most-common-react-useeffect-problems-and-how-to-fix-them
React.useEffect Hook – Common Problems and How to Fix Them
October 14, 2021 - React Hook useEffect has a missing dependency: 'user'. Either include it or remove the dependency array.
🌐
Reddit
reddit.com › r/nextjs › useeffect not triggering
r/nextjs on Reddit: useEffect not triggering
May 21, 2024 -

I tried to download a small template that has some basic setup with vercel, supabase and next.js. Everything seems to be working but my useEffect does not get triggered so my data stays empty. I mainly just copied the Code from the template. Here is the addition, i only get the Console log the the Component is rendered, and the supabase Client gets all the correct data.

'use client'
import { createClient } from '@/utils/supabase/client'
import { useEffect, useState } from 'react'

export default function Page() {
  const [beachscore, setBeachscore] = useState<any[] | null>(null)
  const [error, setError] = useState<any>(null) 

  const supabase = createClient()

  useEffect(() => {
    console.log('useEffect triggered') // Log when useEffect is triggered
    const getData = async () => {
      try {
        console.log('Fetching data from BeachScore table...')
        const { data, error } = await supabase.from('BeachScore').select()
        if (error) {
          throw error 
        }
        console.log('Data fetched:', data)
        setBeachscore(data)
      } catch (error) {
        console.error('Error fetching data:', error)
        setError(error)
      }
    }
    getData()
  }, []) // No dependencies specified

  console.log('Component rendered') // Log when component is rendered

  if (error) {
    return <div>Error fetching data: {error.message}</div> 
  }

  return <pre>{JSON.stringify(beachscore, null, 2)}</pre>
}
'use client'
import { createClient } from '@/utils/supabase/client'
import { useEffect, useState } from 'react'


export default function Page() {
  const [beachscore, setBeachscore] = useState<any[] | null>(null)
  const [error, setError] = useState<any>(null) 


  const supabase = createClient()


  useEffect(() => {
    console.log('useEffect triggered') // Log when useEffect is triggered
    const getData = async () => {
      try {
        console.log('Fetching data from BeachScore table...')
        const { data, error } = await supabase.from('BeachScore').select()
        if (error) {
          throw error 
        }
        console.log('Data fetched:', data)
        setBeachscore(data)
      } catch (error) {
        console.error('Error fetching data:', error)
        setError(error)
      }
    }
    getData()
  }, []) // No dependencies specified


  console.log('Component rendered') // Log when component is rendered


  if (error) {
    return <div>Error fetching data: {error.message}</div> 
  }


  return <pre>{JSON.stringify(beachscore, null, 2)}</pre>
}
🌐
Reddit
reddit.com › r/reactjs › my useeffect in context.js is not triggering at all. i am trying update state within it
r/reactjs on Reddit: My useEffect in Context.js is not triggering at all. I am trying update state within it
September 8, 2022 -

I am trying to setState inside useEffect but the useEffect is not getting triggered at all

import React, { useEffect, useState } from 'react'

import items from './data'


const RoomContext = React.createContext();



const RoomProvider = ({children}) => {
   
    const [state, setState] = useState({
        rooms: [],
        sortedRooms: [],
        featuredRooms: [],
        loading: true,
    })


    const formatData =(items) => {

        let tempItems = items.map((item)=> {
            let id = item.sys.id;
            let images = item.fields.images.map(image => image.fields.file.url);
        
            let room= {...item.fields, images,id};

            return room;
        
        });

        return tempItems;


    }

  
    useEffect(()=> {
        
        console.log(items)
        let rooms= formatData(items);
        console.log(rooms)
        let featuredRooms = rooms.filter(room => room.featured === true)
        console.log("aaaaaaa",featuredRooms)
        
        setState({
            rooms,
            sortedRooms: rooms, 
            featuredRooms,
            loading: false
        })
        
        console.log("render")
    },[state])

    
  console.log("dying")

  return (
    <RoomContext.Provider value={{state,setState}}>
    
        {children}
    
    </RoomContext.Provider>
  )
}

const RoomConsumer = RoomContext.Consumer;

export { RoomContext, RoomProvider, RoomConsumer };
🌐
Reddit
reddit.com › r/reactjs › how to fix the issue of useeffect not triggering on route change even after feeding in params object's property as dependency?
r/reactjs on Reddit: How to fix the issue of UseEffect not triggering on route change even after feeding in Params Object's property as dependency?
September 23, 2022 -

Here's my App.js component

App.js

function App() {
  return (
    <GithubProvider>
      <AlertProvider>
        <Router>
          <div className="flex flex-col justify-between h-screen">

            <Navbar />

              <main className='container mx-auto px-3 pb-12'>
                <Alert />

                <Routes>
                <Route path="/" element={<Home />} />

                <Route path="/about" element={<About />} />
                <Route path="/user/:login" element={<User />} /> {/* ISSUE */}

                <Route path="*" element={<NotFound />} />

              </Routes>


              </main>

            <Footer />

          </div>
        </Router>
      </AlertProvider>
    </GithubProvider>
   
  );
}

The route change to the user component happens in Home Component, I search for a github profile,
a lift of profiles are displayed, I click on the visit profile button on the profile card, which Links me to User component

UserItem.js:

import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'


const UserItem = ({user: {login, avatar_url}}) => {

    return (
        <div className='card shadow-md compact side bg-base-600'>
        <div className='flex-row items-center space-x-4 card-body'>
          <div>
            <div className='avatar'>
              <div className='rounded-full shadow w-14 h-14'>
                <img src={avatar_url} alt='Profile' />
              </div>
            </div>
          </div>
          <div>
            <h2 className='card-title'>{login}</h2>
            <Link
              className='text-base-content text-opacity-60'
              to={`/user/${login}`}
            >
              Visit Profile {/* TRIGGERING HERE!!!!!!!!!!! */}
            </Link>
          </div>
        </div>
      </div>
    )
}


UserItem.propTypes = {
    user: PropTypes.object.isRequired,
}

export default UserItem;

My user Component where the function getUser needs to be triggered->
The function getUsers works fine as when i used it outside an useEffect, it did give me the right response from the fetch call inside.

User.js

import React, { useEffect, useContext } from 'react'
import {FaCodepen, FaStore, FaUserFriends, FaUsers} from 'react-icons/fa'
import { Link } from 'react-router-dom'
import GithubContext from '../context/github/GithubContext'
import { useParams } from 'react-router-dom'
import Spinner from '../components/layout/Spinner'
import RepoList from '../components/repos/RepoList'





export const User = () => {

    const params = useParams()
    
    
    const { getUser, user, loading, getUserRepos, repos } =
    useContext(GithubContext)
    
    console.log("params", params, "login", params.login) // WORKS FINE
    
    
    useEffect ( () => {
        console.log("use-effect", getUser, "", params.login)
        getUser(params.login)
        getUserRepos(params.login)

    },[params.login]) // DOESNT TRIGGER WITH [] or [params.login]

    console.log( "user-check",user) // user object empty
    
    const {
        name,
        type,
        avatar_url,
        location,
        bio,
        blog,
        twitter_username,
        login,
        html_url,
        followers,
        following,
        public_repos,
        public_gists,
        hireable,
      } = user


      console.log("YES THIS PAGE") // Here I was checking whether page is being mounted and YES it is being mounted 


    const websiteUrl = blog?.startsWith('http') ? blog : 'https://' + blog


    if(loading){
        return <Spinner />
    }



  return (<> TYPICAL INFORMATION DISPLAY UI </>)
}
Find elsewhere
🌐
React
react.dev › reference › react › useEffect
useEffect – React
If your Effect wasn’t caused by an interaction (like a click), React will generally let the browser paint the updated screen first before running your Effect. If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), replace useEffect with useLayoutEffect.
🌐
GitHub
github.com › testing-library › react-testing-library › issues › 215
useEffect not triggering inside jest · Issue #215 · testing-library/react-testing-library
November 3, 2018 - The useEffect hook is not executed correctly inside a jest environment after calling render(<Test />).
Author   peterjuras
🌐
GitHub
github.com › vercel › next.js › discussions › 63996
How to Troubleshoot useEffect Not Triggering API Call on State Change in Next.js 14? · vercel/next.js · Discussion #63996
To clarify, we are indeed changing ... that reflect the state's current value. The issue arises when we attempt to trigger an API call through useEffect following a state change....
Author   vercel
🌐
GitHub
github.com › react-hook-form › react-hook-form › issues › 12117
issue: useEffect not triggering on value watched with useFieldArray · Issue #12117 · react-hook-form/react-hook-form
July 19, 2024 - Version Number 7.49.3 Codesandbox/Expo snack code sandbox Steps to reproduce Setup a simple form use field array useEffect on watch of field array key when editing field within field array. useEffect not triggered Expected behaviour useE...
Author   CutiePi
🌐
Reddit
reddit.com › r/react › useeffect not running properly
useEffect not running properly : r/react
August 30, 2023 - When I select the username in the drop-down, it is not calling the api for the first time. I have to select it twice although I can see the username value changing in the first attempt only ... const [value, setValue] = useState(0); useEffect(() => { const myApiCall = async () => { const data = await apiCall(); // handle data }; myApiCall(); }, [value]);
🌐
Medium
medium.com › @joabi › react-interview-why-those-useeffect-hooks-are-not-working-as-expected-03aaf79df4a5
React Interview: Why those useEffect hooks are not working as expected? | by Julie J. | Medium
November 3, 2023 - It displays the current values of count1 and count2. ... The issue with the second counter not updating as expected is due to the lack of specifying a dependency array in the useEffect hooks.
🌐
Reddit
reddit.com › r/react › function specified in useeffect hook doesn't run
r/react on Reddit: Function specified in useEffect hook doesn't run
October 14, 2021 -

Hello,

I have a functional object which has three variables managed by the useState hook. These are categories, activeCategories and shownGames. For now I need something simple - run a function when categories update. I am using useEffect hook but it doesn't seem to work.

This is the code for the needed parts - https://pastie.io/uyakqz.js

I use JSON.stringify to check for the category updates (found that solution on StackOverflow). The issue is that the function specified in the useEffect hook doesn't run (it only runs when I load my page). Any help is appreciated!

🌐
React
react.dev › learn › you-might-not-need-an-effect
You Might Not Need an Effect – React
// 🔴 Avoid: Chains of Effects that adjust the state solely to trigger each other · useEffect(() => { if (card !== null && card.gold) { setGoldCardCount(c => c + 1); } }, [card]); useEffect(() => { if (goldCardCount > 3) { setRound(r => r + 1) setGoldCardCount(0); } }, [goldCardCount]); useEffect(() => { if (round > 5) { setIsGameOver(true); } }, [round]); useEffect(() => { alert('Good game!'); }, [isGameOver]); function handlePlaceCard(nextCard) { if (isGameOver) { throw Error('Game already ended.'); } else { setCard(nextCard); } } // ...
🌐
GitHub
github.com › react-hook-form › react-hook-form › issues › 4299
`useEffect` not triggering when `errors` object updates on `reValidate` · Issue #4299 · react-hook-form/react-hook-form
February 26, 2021 - Describe the bug When subscribing to changes to errors within useEffect, the callback does not fire when the errors object updates on reValidate. To Reproduce Steps to reproduce the behavior: Go to https://codesandbox.io/s/react-hook-for...
Author   ryanwalters
🌐
Stack Overflow
stackoverflow.com › questions › 72393420 › react-useeffect-not-triggering-when-dependency-has-changed
React.useEffect not triggering when dependency has changed
Edit: I found the solution to this! See my answer below. So essentially, I have a slice of state that is updating but not triggering the useEffect that has it as a dependency: const [editablePartic...