Will a react component reset its state when it re-renders?

Viewed 8503

I have a react functional component and declares my state as:

const [myState, setMyState] = useState<boolean>(true);

When this function re-renders when one of my props changes, does myState get reset to true ?

3 Answers

Value of state will not get altered automatically after a re-render.

In react, it is always one-way transition:

Change of state will trigger the render() method.

Render method will not trigger state change.

No, The state will remain as it is until your component unmounts.

If you want to trigger something while unmounting then you can use useEffect hook.

Example:

useEffect(()=>{
//code

return ()=>{
  //unMount Code
}
},[])

For example your component have to props id, title when chnage id or title you want to set myState to true. your component should be:

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

const MyComponent = ({id, title}) => {
  const [myState, setMyState] = useState(true);

  useEffect(()=>{
    setMyState(true);
  },[id, title])

  return (<div>your code</div>)

}
Related