'How to call a function immediately
I write my request in my parent Component with code below:
useEffect(() => {
// my request
}, [])
As we all know, useEffect of parent component will implement after child component, so this request will be implemented after all child components rendered. How can I call my request immediately before my child component's useEffect?
Solution 1:[1]
The order of execution of useEffect in a simple parent child component like this
<Parent>
<Child />
</Parent>
is, child useEffect first and then parent's.
If you want child to wait for parent's useEffect, you can use a conditional to show something else till then:
const [showChild, setShowChild] = useState(false);
useEffect(() => {
/* other activies */
setShowChild(true);
});
return (
<>
<other?omponents />
{showChild && <Child />
<other?omponents / >
</>
);
Solution 2:[2]
Don't put you function into useEffect, just in the component body:
export default function YourComponent() {
// Your logic here
return (
...
);
}
Because your component is just a function too, your function will be called immediately.
Solution 3:[3]
Simply, put statement of parent useEffect to top of child component's useEffect.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3840170 |
| Solution 2 | Igor Gonak |
| Solution 3 | RBT |
