Home > OS >  How to make a state disappear after some time (React)?
How to make a state disappear after some time (React)?

Time:05-09

I have a state in useState hook and I want to make it disappear after a particular time frame. I tried using setTimeout() but it does not work.

export const Profile = () => {
  let { username } = useParams();

  const [bio, setBio] = useState("");
  const [country, setCountry] = useState("");
  const [updated, setUpdated] = useState(""); // I am printing this 'updated' value in my return statement

Return statement

<h3>{updated}</h3> // I want this 'updated' text to disappear after 3 sec

CodePudding user response:

Use a combination with useEffect() and setTimeout() in the following manner:

let timeoutId = null;

export function App(props) {

  const [updated, setUpdated] = useState("");

  useEffect(() => {
    // if there's a message in updated
    if(updated.length > 0) {
      //remove previous timeout if any
      if(timeoutId !== null) {
        clearTimeout(timeoutId);
      }

      // create a timeout to remove it
      timeoutId = setTimeout(() => setUpdated(""), 3000);
    }
    
    // cleanup
    return () => {
      if(timeoutId !== null) {
        clearTimeout(timeoutId);
      }
    }
  }, [updated])


  return (
    <div className='App'>
      <button onClick={() => setUpdated("You have successfully did something!")}> setUpdated("You have successfully did something!") </button>
      <hr />
      {updated}
    </div>
  );
}

Demo: https://playcode.io/895066

  • Related