'Difference between useState and useEffect

I use useState instead of useEffect and it works fine for displaying data (why?)

React.useState(() =>getMovies(), [])

Note : I added console.log and I get same results



Solution 1:[1]

When a function is passed to useState, this is signaling to React to use lazy initialization - the function will be invoked to calculate the initial value only when the component mounts.

If the value to be put into state can be calculated/retrieved synchronously, this is probably the best design pattern to use - it's short and doesn't require you to later differentiate between whether the state value is undefined or populated.

const [stateValue, setStateValue] = useState(calculateExpensiveInitialStateValue);

The time to use useEffect is when the value to be populated can't be computed synchronously, in which case the best approach is to have both useState (for the state) and useEffect (to indicate that you want to run a function to retrieve the state value just once).

While you theoretically can have a line just like

React.useState(() =>getMovies(), [])

it's pretty confusing, because

  • The resulting state value returned isn't used
  • useState doesn't accept a second argument dependency array

useEffect is more suited for the task because it doesn't have a return value (unlike useState), and is more flexible, because it does accept a dependency array. useEffect much more clearly indicates to readers of the code "This callback should run only when the dependency array changes."

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance