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
Discussions

reactjs - useEffect doesn't trigger at all - Stack Overflow
For some reason I cannot trigger my useEffect. It is a simple counter of seconds. I added console.log just to check if it will ever trigger but it doesn't at all. The interesting part is that React More on stackoverflow.com
🌐 stackoverflow.com
Function specified in useEffect hook doesn't run
Prolly a very stupid question but did you try console logging to check whether categories is changing or not? More on reddit.com
🌐 r/react
18
2
October 14, 2021
reactjs - useEffect doesn't run after rendering - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm kind of confused about how useEffect is triggered ... More on stackoverflow.com
🌐 stackoverflow.com
Bug: useEffect not triggering on [deps] change
I stumbled upon this issue which initially I thought is React bug, but upon further investigation React Query seems like the next best candidate. Minimal project is created to demonstrate the probl... More on github.com
🌐 github.com
26
September 2, 2021
🌐
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 - By Iva Kop React hooks have been around for a while now. Most developers have gotten pretty comfortable with how they work and their common use cases. But there is one useEffect gotcha that a lot of us keep falling for. The use case Let's start with ...
🌐
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!

Top answer
1 of 4
6

The useEffect hook is guaranteed to run at least once at the end of the initial render.

getData is an async function and the useEffect callback code is not waiting for it to resolve. Easy solution is to chain from the implicitly returned Promise from getData and access the resolved value to update the arrData state. Make sure to remove the state from the useEffect's dependency array so that you don't create a render loop.

The getData implementation could be clean/tightened up by just returning the fetch result, no need to save into a temp variable first.

async function getData() {
  return await fetch(".....")
    .then((res) => res.json());
}

useEffect(() => {
  console.log("if it works, this line should be shown");
  getData().then((data) => {
    setArrData(data);
  });
}, []); // <-- empty dependency so effect called once on mount

Additionally, since arrData is initially undefined, arrData[0] is likely to throw an error. You may want to provide valid initial state, and a fallback value in case the first element is undefined, so you don't attempt to access properties of an undefined object.

const [arrData, setArrData] = useState([]);

...

const data = arrData[0] || {}; // data is at least an object

return (
  <GifCompoment 
    id={data.id}
    name={data.name}
    activeTimeTo={data.activeTimeTo}
    activeTimeFrom={data.activeTimeFrom}
    requiredPoints={data.requiredPoints}
    imageUrl={data.imageUrl}
  />
);
2 of 4
1

You should call state setter insede of Promise

function App() {
    const [arrData, setArrData] = useState();

    function getData() {
        fetch("/api/hidden")
            .then((res) => res.json())
            .then((data) => setArrData(data));
    }

    useEffect(() => {
        console.log("if it works, this line should be shown");
        getData();
    }, []);

    return ...
}
🌐
GitHub
github.com › tannerlinsley › react-query › issues › 2628
Bug: useEffect not triggering on [deps] change · Issue #2628 · TanStack/query
September 2, 2021 - Expected behavior useEffect should register new changes, since every other part of the UI does
Author   Tosheen
Find elsewhere
Top answer
1 of 1
1

As @DennisVash written in his comment:

Why? Because the change to document.documentElement.lang won't trigger the hook. Only a render will trigger the hook, and if lang changed the callback will be executed.

However, since changing the property actually changes the lang attribute value in the DOM, you can use a MutationObserver to track the lang attribute values.

I've created a custom useMutationObserver hook to track mutations in the DOM, and based useLocale on it.

const { useRef, useEffect, useState, useCallback } = React;

const useMutationObserver = (domNodeSelector, observerOptions, cb) => {
  useEffect(() => {
    const targetNode = document.querySelector(domNodeSelector);
    
    const observer = new MutationObserver(cb);
    
    observer.observe(targetNode, observerOptions);
    
    return () => {
      observer.disconnect();
    };
  }, [domNodeSelector, observerOptions, cb]);
}

const options = { attributes: true };

const useLocale = () => {
  const [lang, setLang] = useState(document.documentElement.lang);
  
  const handler = useCallback(mutationList => { 
    mutationList.forEach(mutation => {
      if(mutation.type !== 'attributes' || mutation.attributeName !== 'lang') return;

      setLang(document.documentElement.lang);
    });
  }, []);
  
  useMutationObserver('html', options, handler);

  return lang; // locale[lang]
};

const Demo = () => {
  const locale = useLocale();

  return <div>{locale}</div>;
};

document.documentElement.lang = 'en'; // base lang

ReactDOM.render(
  <Demo />,
  root
);

// example - changing the lang
setTimeout(() => document.documentElement.lang = 'fr', 1000);
setTimeout(() => document.documentElement.lang = 'ru', 3000);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

🌐
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 - It’s essential to understand that useEffect runs after every render by default, but if you provide a dependency array, it will only run when the specified props or state variables change.
🌐
Stack Overflow
stackoverflow.com › questions › 67855074 › react-useeffect-doesnt-trigger-fetch-when-rendering-component
React useEffect doesn't trigger fetch when rendering component
Native Ads coming soon to Stack Overflow and Stack Exchange · Policy: Generative AI (e.g., ChatGPT) is banned · 1 React not rendering data from useEffect · 0 useEffect not rendering before getting to return · 1 React - UseState not triggering rerender following fetch inside useEffect hook ·
🌐
Stack Overflow
stackoverflow.com › questions › 72393420 › react-useeffect-not-triggering-when-dependency-has-changed
React.useEffect not triggering when dependency has changed
... This should work, see codesandbox.io/s/react-hooks-playground-forked-f2ymtt?file=/src/… Can you provide a minimal reproducable example ... If the useEffect isn't getting triggered , the only reason is the dependency is not changing.
🌐
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 };
🌐
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