Home > database >  React Typescript useState Hook doesn´t Update by using "setState" method
React Typescript useState Hook doesn´t Update by using "setState" method

Time:04-24

Good day,

I am coding a React application and have a propblem 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;

I hope i can get here

With friendly greetings

Louis Venhoff

CodePudding user response:

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)}}/>

CodePudding user response:

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

  • Related