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]
};
It confused me because they are not using
useEffect()to read from the local storage, which is a side effect, they are usinguseState(), I would have useduseEffect()thenuseState()to set the value of thestatevariableuseEffect()is being used for the side effect of writing to localStorage, if this was a POST request to an API, willuseEffect()still apply?