Skip to content
Advertisement

How to return from promise inside useEffect

I am creating my first custom hook. I would like the hook to return the deviceType which is the result of a Promise in the hook.

Hook:

JavaScript

Use of hook:

JavaScript

Console:

undefined

I may be having difficulty understanding the useEffect hook but I believe it should just fully run once here.

Is the item being returned still undefined because the Promise has not resolved? If so, then how am I able to use the deviceType inside setScreenOrientation?

When I console.log(deviceType) inside the useEffect hook I get the appropriate response:

2

Thank in advance for the help in understanding this!

Final Edit:

JavaScript

Output (correct):

4

Advertisement

Answer

JavaScript

This should fix the behavior and then deviceType will be accessible through const deviceType = useDeviceType();.

What you seem to be misunderstanding here is how returning values from useEffect work. You can read about it here, but we actually use it to create cleanup functions that will run on our component’s unmount.

Edit: you can also see in React’s docs how custom hooks are supposed to return values.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement