useState & useEffect() hook

useState() hook

useState() hook is a special function which takes one argument. The argument passed to useState is initial state. It returns an array of two entries. The first element is the initial state and the second is a function which is used for updating state. It should be noted that unlike class components, state doesn't have to be an object. It can be a string, number, array, boolean or an object.

useEffect() Hook

useEffect is React hook, which use to handle side effects functions. Side Effects are those functions that interact with the outside world, or out of React Js ecosystem and with useEffect, we can separate them into another Function.

  1. useEffect hook must declare inside the component (top-level, don't declare them in the block), it will give several advantages

  2. It will have accessibility to those data that are required to use in side effects. It can also update the data later, based on the dependencies and changes.

About the Syntax:

The first argument in useEffect is to give side effects function. The second argument is the dependencies array which gives instructions to useEffect hook when to run and when to not. Let's see this more closely: If you don't give dependences array, only pass the first argument, then useEffect runs whenever your component renders/re-renders. If you give an empty dependences array, then useEffect runs once(when your component renders the first time, after that, it will not run unless you refresh the page). If you give something in the dependencies array, then useEffect will run once by default after the component finish rendering. After that, whenever the value of elements in the dependences array change, then useEffect will run again.

Why should we use useEffects()?

There are several cases where you should consider useEffects. Some of them are:

Suppose you are fetching some data online to display movie titles, ratings & you have used handler(Function with the synthetic event) or used inline Functions to get that data. So, what will happen is your component rendering will be stuck when the thread of execution reaches this point until you get the data from outside of the world. By seeing the first point, we can move those side effects to the useEffect hook so that our components can load/render. After completing the rendering process, React Engine will fire the useEffect hook to run the side effects code and update the component data. We should useEffect, when your component depends on the outside world data, and we can not guarantee that data will come or not (maybe the server is down there). So, Instead of throwing errors and stop other components from being rendered, move them into useEffect hook. When you are using browser API (including Timer function, fetch API, local storage and for more browser API, refer to this: MDN Browser API).