DEV Community

shandamengcheng
shandamengcheng

Posted on

2 1 1 1 1

Several ways to handle request side effect that you should know

In React, useEffect is commonly used to handle side effect, including handle request side effects.

However, when it comes to handling requests, it's common to use async/await, but passing an async function as the first argument of useEffect will result in an error.

This is because useEffect expects a function that returns void, but async functions return a promise.

Therefore, there are several ways to handle request side effects without errors that you should know.

1. use an async function expression


const [data, setData] = useState(null);

useEffect(() => {
    const fetchData = async () => {
        const result = await fetch(
            'YOUR_URL_HERE'
        );
        setData(result.data);
    }
    fetchData();
}, []);
Enter fullscreen mode Exit fullscreen mode

You can also abstract the function expression into a useCallback hook outside the useEffect so that you can use it in other places:

const [data, setData] = useState(null);

// useCallback can accept an async function as its argument
const fetchData = useCallback(async () => {
    const result = await fetch(
        'YOUR_URL_HERE'
    );
    setData(result.data);
}, [])
useEffect(() => {
   fetchData()
}, [fetchData])
Enter fullscreen mode Exit fullscreen mode

2. use an IIFE

const [data, setData] = useState(null);

useEffect(() => {
    (async () => {
        const result = await fetch(
            'YOUR_URL_HERE'
        );
        setData(result.data);
    })()
}, [])
Enter fullscreen mode Exit fullscreen mode

3. use Promise.then

const [data, setData] = useState(null);

useEffect(() => {
    fetch( 'YOUR_URL_HERE')
        .then(result => setData(result.data));
}, [])
Enter fullscreen mode Exit fullscreen mode

4. use function declaration

const [data, setData] = useState(null);
useEffect(() => {
    async function fetchData() {
        const result = await fetch(
            'YOUR_URL_HERE'
        );
        setData(result.data);
    }
    fetchData();
}, [])
Enter fullscreen mode Exit fullscreen mode

Also, you can abstract this function declaration into a useCallback hook outside the useEffect so that you can use it in other places.

Hope these ways can work for you. :)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay