-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate-State-Async
More file actions
31 lines (24 loc) · 799 Bytes
/
Update-State-Async
File metadata and controls
31 lines (24 loc) · 799 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// If you're setting state in React and immediately trying to access the state,
// you may run into issues where the state hasn't updated yet.
// This is because state updates are asynchronous in React.
// To solve this issue, you can use the useEffect hook to perform an action after the state has updated.
// Here's an example:
import { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
// This code will run after the state has updated
console.log(data);
}, [data]);
useEffect(() => {
// This code will run once, when the component mounts
fetchData();
}, []);
function fetchData() {
// This function updates the state
setData('my data');
}
return (
<div>{data}</div>
);
}