Reputation: 2143
Reactjs does not update the new value when I use usestate hook: Look at this example:
import React, { useState, useEffect } from "react";
const Dictionary = () => {
const [name, setName] = useState("Bob");
useEffect(() => {
updateName();
}, []);
const updateName = () => {
setName("John");
console.log("name:", name); // prints "Bob"
setName(myName => "John");
console.log("name:", name); // prints "Bob"
};
return (
<>
<h2>Dictionary</h2>
</>
);
};
I have tried to make use of promises but I don't get a solution either.
const updateName = async () => {
await uName("John");
console.log(name); // "Bob"
};
const uName = (nam) => {
return new Promise((res, rej) => {
setName(nam);
res();
});
};
Upvotes: 0
Views: 62
Reputation: 955
Update your code as:
import React, { useState, useEffect } from "react";
const Dictionary = () => {
const [name, setName] = useState("Bob");
useEffect(() => {
updateName();
}, []);
useEffect(() => {
/* Use this useEffect to perform actions when name get updated. */
console.log(name);
}, [name]);
const updateName = () => {
setName("John");
console.log("name:", name); // prints "Bob"
setName(myName => "John");
console.log("name:", name); // prints "Bob"
};
return (
<>
<h2>Dictionary</h2>
</>
);
};
Upvotes: 0
Reputation: 11397
React is still Javascript, and it only updates values on the next run.
See commented code below:
const updateName = () => {
setName("John"); // Updates the name. Will be "John" on the next render
console.log("name:", name); // Should print "Bob"
setName(myName => "John"); // Will run `myName => "John"` on the next render.
console.log("name:", name); // Should print "Bob"
};
When you run set
hooks, it marks the value as updated and triggers a new render as soon as this render
is done.
You can't change the update the value of state mid-render, as the code at the top of the render()
would have run with the old value.
Directly from a the React documentation:
component schedules a UI update by calling setState() [...] Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen
Upvotes: 1