useEffect on async operation



I’m a little confused when to use useEffect() the majority of the examples I see only use useEffect() to pull data from an API and other examples of side effects, but I haven’t seen people using useEffect() when sending POST request when the component will mount.

Then I was taking the course of Epic React, this custom hook confused me:

const useLocalStorageState = (key, value = "") => {
  const [state, setState] = React.useState(() => window.localStorage.getItem(key) || value)

  React.useEffect(() => {
    window.localStorage.setItem(key, state)
  }, [key, state]);

  return [state, setState]
};
  1. It confused me because they are not using useEffect() to read from the local storage, which is a side effect, they are using useState(), I would have used useEffect() then useState() to set the value of the state variable

  2. useEffect() is being used for the side effect of writing to localStorage, if this was a POST request to an API, will useEffect() still apply?

Answer

It confused me because they are not using useEffect() to read from the local storage, which is a side effect, they are using useState(), I would have used useEffect() then useState() to set the value of the state variable

A good reason to use useEffect is that it can prevent the call to localStorage.getItem(), for every render.

However, this would be needed if you did call localStorage.getItem(), for every render.

const [state, setState] = React.useState(
  () => window.localStorage.getItem(key) || value
)

In this example, getItem is not called for each render. It’s only used in the callback passed to getState(). This is the initial value and it will only be used on the very first render. So, it solves the same problem.

useEffect() is being used for the side effect of writing to localStorage, if this was a POST request to an API, will useEffect() still apply?

It may be useful in useEffect, but it depends on the situation. In many cases a POST request could be triggered when the user presses a button (submit or click events). In those cases the POST request is likely triggered from event handlers.

If you need to always do a POST on specific React lifecycle events (update, mount, etc), they would need to be in useEffect.



Source: stackoverflow