0

I am coding a React application and have a problem with the state management.

I added a State "headlineState" which is a boolen which is by default false. Also i have a Callback Method which updates this state.

When the Callback value gets executed, my state doesnt Change.

I implemented a useEffect hool which displays the changes of my state in an "window.alert", and in this hook i see that my state is changing.

But after that, my state returns directly back to false.

function App() {
  
  const [headlineState, setHeadlineState] = useState<boolean>(false);
  
  useEffect(() =>  {
     window.alert("HS changed" + headlineState)
  }, [headlineState]);

  const moveHeadline = (value:boolean) => {
    setHeadlineState(value);
  }

  return (
    <ThemeProvider theme={theme}>
      <div className="App">
        <div className="headerDiv">
          <Header isOnSubpage={headlineState} backBtnClick={() => { moveHeadline(false) }}/>
        </div>
        <div className="contentPageDiv">
          <ContentPage />
        </div>
      </div>
    </ThemeProvider>
  );
}

export default App;
1
  • 2
    where do you change it to true? In your code this is false by default and you only change it to false (moveHeadline(false)) Commented Apr 23, 2022 at 12:20

2 Answers 2

1

I am not sure what you want to achieve but in case of searching solution to set state to opposite one, you can update your function like this

<Header isOnSubpage={headlineState} backBtnClick={() => {moveHeadline(!headlineState)}}/>
Sign up to request clarification or add additional context in comments.

Comments

0

The "state returns directly back to false" because you set it like so in moveHeadline(false).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.