Alvi
Alvi

Reputation: 3

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

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

Upvotes: 0

Views: 30

Answers (1)

DecPK
DecPK

Reputation: 25408

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 Infinite re-rendering. You can prevent it by passing empty dependency array to useEffect.

If you want to see the Infinite re-rendering Please see CODESADNBOX LINK

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

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

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

Upvotes: 1

Related Questions