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.
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
useEffectwould have caused unlimited re-rendering. You can prevent it by passingempty dependency arraytouseEffect.
function Any() {
const [content, setContent] = useState(() => <p>No movies found</p>);
useEffect(() => {
setTimeout(() => {
console.log('changing state');
setContent('');
}, 2000);
}, []);
return <section>{content}</section>;
}
