🌐
GitHub
github.com › facebook › react › issues › 22272
Feature Request - useEffect - Provide boolean values on whether dependency has changed. · Issue #22272 · facebook/react
September 8, 2021 - I can imagine that this could result in some performance decrease but we could consider making a dedicated version of useEffect like useObservableEffect or something like that (I'm not great at naming so i'm sure the community can come up with a better name :D) Currently we use a workaround which requires using a ref to hold the previous values and comparing them inside the useEffect.
Author   yamarco
Discussions

reactjs - useState with boolean value in react - Stack Overflow
This is the expected behavior. You may want to use useEffect to access the latest value. Here is a thread discussing the same issue: useState set method not reflecting change immediately More on stackoverflow.com
🌐 stackoverflow.com
javascript - React useState setter is not working on a boolean value - Stack Overflow
I tried updating a state value using its setter from the useState hook, but it wouldn't update. The same setter is working in a different function while setting the value true. To make sure that the More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to check if state default boolean false is changing to true with React Hook useEffect - Stack Overflow
Your boolean.current value will never be changed as it's useEffect callback behaves as contructor function which will run only once as we have empty dependency inside it. More on stackoverflow.com
🌐 stackoverflow.com
reactjs - How do we check the boolean value in useEffect in react hooks? - Stack Overflow
You can add another useEffect which watches this change, useEffect takes a second argument which is dependency array and the effect gets called if any of the dependency array value changes . In this case since you need to make a decision based on the nomStatus, you can add it as a dependency ... More on stackoverflow.com
🌐 stackoverflow.com
August 27, 2021
🌐
Reddit
reddit.com › r/reactjs › should i use useeffect when its dependency is true/false and is directly from props?
r/reactjs on Reddit: Should I use useEffect when its dependency is true/false and is directly from props?
May 12, 2022 -

Can’t we just use the prop value directly instead of wrapping it in a useEffect?

Say,

Component = ({bool}) => {

If (bool) playSound()

return … }

Versus:

UseEffect(() => if(bool) playSound(), [bool])

These two cases have same behavior.

Update: It’s better to use useEffect, which only fires the side effect when the dependency changes when a component re-renders. It guards against incorrectly triggering the side effect if the dependency did not change value upon component re-render.

Top answer
1 of 6
25

setIsLoading is an async function and you cannot get the state value immediately after update.

setState actions are asynchronous and are batched for performance gains. setState() does not immediately mutate this. Thus the setState calls are asynchronous as well as batched for better UI experience and performance. This applies on both functional/Class components.

From React documentation

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. You could read more about this here

If you want to get the updated state value then use useEffect hook with dependency array. React will execute this hook after each state update.

const {useEffect, useState } = React;

const App = (props) => {
  const [isLoading, setIsLoading] = useState(false)
  const buttonHandler = () => {
    setIsLoading(current => !current)
  }

  useEffect( () => {
    console.log(isLoading);
}, [isLoading]);

  return (
    <div>
      <button onClick={buttonHandler} type="button">
        Change
      </button>

      {isLoading? "Loading...": null}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

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

2 of 6
4

This is the expected behavior. You may want to use useEffect to access the latest value.

Here is a thread discussing the same issue: useState set method not reflecting change immediately

Hope this helps!

🌐
Stack Overflow
stackoverflow.com › questions › 70769000 › react-usestate-setter-is-not-working-on-a-boolean-value
javascript - React useState setter is not working on a boolean value - Stack Overflow
So sorry for the question, but the problem was due to a template issue, the click also triggered the function which sets the value to true. The confusion arose because the state update useEffect was not called, and that lead me to different line of investigation.
🌐
Stack Overflow
stackoverflow.com › questions › 57317696 › how-to-check-if-state-default-boolean-false-is-changing-to-true-with-react-hook
javascript - How to check if state default boolean false is changing to true with React Hook useEffect - Stack Overflow
Not sure if I should use usePrevious for that, because when comparing numbers it works well with this code, but it seems that it is not working when I am trying to check if default boolean is changing. const MemoryPageTwo = ({ disabledAllCards }) => { const boolean = useRef(null); const [ isCurrentBoolean , setLevel ] = useState(false); useEffect(() => { console.log(isCurrentBoolean); if(isCurrentBoolean) { console.log('currentBoolean'); } }, [isCurrentBoolean]); useEffect(() => { const storedBoolean = disabledAllCards ; boolean.current = storedBoolean; return () => storedBoolean }, []); // us
🌐
Ais
ais.com › home › blog › hooked on react: usestate and useeffect
Hooked on React: useState and useEffect - Applied Information Sciences
August 28, 2023 - Having this isn’t required if you leave it as useState(true). React will know that it is a Boolean, and lastly, we have the initial state, which is set to false. This is where you can have the initial value to be whatever you want when the component first renders.
🌐
DEV Community
dev.to › alexkhismatulin › update-boolean-state-right-with-react-hooks-3k2i
Update boolean state right with React Hooks - DEV Community
May 11, 2020 - Creating a boolean state and a toggle method for it is a pretty common use case. The spinnet is 100% correct in terms of functionality. But it could be better in terms of performance. Let's see how it can be improved. First things first – useCallback does nothing in this implementation.
Find elsewhere
🌐
Lightrun
lightrun.com › answers › facebook-react-feature-request---useeffect---provide-boolean-values-on-whether-dependency-has-changed
Feature Request - useEffect - Provide boolean values on whether dependency has changed.
+1 on this ticket, this is indeed similar to what I’ve posted on https://github.com/facebook/react/issues/22132 (in particular probably the same solution as proposed by @Sangrene https://github.com/facebook/react/issues/22132#issuecomment-901819460) I don’t know what is the best solution for sure, but there is definitely something off in the way useEffect is working currently. It has been going unnoticed, but now that react-hooks/exhaustive-deps is on in many projects (thanks Next.js 😃) it becomes visible that most of us are struggling to use it. The concepts of “dependency” and “effect trigger” are not the same and thus should probably not share the same argument.
🌐
YouTube
youtube.com › techinfo yt
useState Boolean Value Issue | React Hooks Tutorials - YouTube
video contains: solution of Boolean value with useState HookWelcome to React JS Hooks Series in this video you will learn about complete react js hooks with...
Published   March 11, 2022
Views   2K
Top answer
1 of 2
1

You can add another useEffect which watches this change, useEffect takes a second argument which is dependency array and the effect gets called if any of the dependency array value changes .

In this case since you need to make a decision based on the nomStatus, you can add it as a dependency to your useEffect

useEffect(() => {
  if (nomStatus) {
    setShowCalender(true);
  }
}, [nomStatus]);
2 of 2
1

You can't since React state updates are asynchronously processed, the nomStatus state update won't be available until the next render cycle. Use the res.data[0].status value to set the showCalendar state.

const [nomStatus, setNomStatus] = useState(false);

useEffect(() => {
  const fetchData = async () => {
    const email = localStorage.getItem("loginEmail");
    try {
      const res = await Axios.get(
        "http://localhost:8000/service/activeStatus",
        {email}
      );
      setNomStatus(res.data[0].status);
      console.log("Get status data :" + res.data[0].status);
      if (res.data[0].status){
        setShowCalender(true);
      }
    } catch (e) {
      console.log(e);
    }
  };
  fetchData();
}, []);

Or you can use a second useEffect hook with a dependency on nomStatus state update to set the showCalendar state.

useEffect(() => {
  const fetchData = async () => {
    const email = localStorage.getItem("loginEmail");
    try {
      const res = await Axios.get(
        "http://localhost:8000/service/activeStatus",
        {email}
      );
      setNomStatus(res.data[0].status);
      console.log("Get status data :" + res.data[0].status);
    } catch (e) {
      console.log(e);
    }
  };
  fetchData();
}, []);

useEffect(() => {
  if (nomStatus){
    setShowCalender(true);
  }
}, [nomStatus]);
🌐
DevPress
devpress.csdn.net › react › 62ec4bfb89d9027116a109d6.html
Update boolean state right with React Hooks_reactnative_weixin_0010034-React
August 5, 2022 - Recently I found a construction like this while doing code review: const MyComponent = (props) => { const [isToggled, setIsToggled] = React.useState(false); const toggle = React.useCallback(() => set weixin_0010034 React
🌐
Coding Beauty
codingbeautydev.com › home › posts › how to toggle a boolean state in react
How to Toggle a Boolean State in React - Coding Beauty
December 27, 2022 - We can do this by creating a ref flag variable having an initial value of false in the first render, and change its value to true for all subsequent renders. JavaScriptCopied! import { useEffect, useRef, useState } from 'react'; import axios ...
🌐
Stack Overflow
stackoverflow.com › questions › 76719020 › useeffect-with-boolean-updates-too-late
reactjs - UseEffect with Boolean updates too late - Stack Overflow
July 19, 2023 - You could have the handleRadioClick() function return the value you need and then use that in the generate2() function, or you could make use of a useEffect hook and pass the boolean in the dependency array, so you can run the generate2() logic ...
🌐
Stack Overflow
stackoverflow.com › questions › 66208718 › useeffect-not-validating-boolean-values-to-perform-some-action
reactjs - useEffect not validating Boolean values to perform some action - Stack Overflow
February 15, 2021 - Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I using contextApi for state management, i have checkbox, on checked and unchecked, trying to dispatch ome actions to the store. sample code: import { store } from '../../../shared/store'; function GPSPosition() { const [isEnable, setCheckBoxEnable] = useState(false) useEffect(() => { console.log(isEnable, "in use effect"); setCheckBoxEnable(isEnable) console.log(isEnable, "in use effect after"); if (isEnable) { dispatch({ type: "stopsendingdata", stop_sending: isEnable, data: 'GPS' }) } else {