Home > other >  React.js: why setTimeout doesn't work changing jsx element
React.js: why setTimeout doesn't work changing jsx element

Time:08-14

It doesn't change the jsx element after setTimeout call. Not changing the content variable inside section jsx element. Note that I am using section element because it's part of my project.

function Any() {
  
let content = <p>No movies found</p>;
  setTimeout(() => {
    content = "";
  }, 2000);

  return (
      <section>{content}</section>
  );
}

CodePudding user response:

It is changing the content to '' but the component is not rendering it after it gets changed so it looks like it is not changing.

CODESANDBOX LINK

One way to do is to use useState here.

You should use useEffect here.

React is smart enough to figure it out when to render and when to not. If you change state with the same primitive current state then react won't re-render it. otherwise without useEffect would have caused unlimited re-rendering. You can prevent it by passing empty dependency array to useEffect.

function Any() {
    const [content, setContent] = useState(() => <p>No movies found</p>);

    useEffect(() => {
        setTimeout(() => {
            console.log('changing state');
            setContent('');
        }, 2000);
    }, []);

    return <section>{content}</section>;
}
  • Related