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?
getItemintouseEffect?useEffectwhich can help you avoid side effects with that re-renders?stateof the game so every time I make a move, gets stored in localstorage and if I refresh the page, I see thestateof the game who it was before I refreshed the page. I think the author is usinguseStateto get the state every time the state changes but isn't this doable via useEffect as well if I don't pass the dependency array? This looks like a shortcut by just usinguseState(). Thoughts?