Learning about React (Chapter III)

Learning about React (Chapter III)

React Hooks(UseState & UseEffect)

This is the third week of December 2022, and I have learned about react hooks, a very interesting topic. I am starting with the useState hook. What is it?

The useState hook lets us "remember" a value within a component function. Since our component function may be called many times throughout the lifecycle of the component, any variable we declare normally (i.e. with let myVariable = ...) will get reset. With useState, React can remember a state variable for us, making sure it gets passed into our component instance correctly.

The useState hook takes a single argument, our initial state, and returns an array containing two elements:

state - the current state

setState - a function to update our state

Also, there are some rules while using the useState hook. First of all, it needs to be used inside the function & at the top of the function. It only works inside the function & order basis. So if we are using multiple useState hook then we need to make sure that the order is maintained.

so for example - While doing the assignment of CYF, In the `<Bookings />` component, I have declared a new state `bookings` with the corresponding setter function `setBookings` to hold the `FakeBookings` data. Instead of passing `FakeBookings` directly to the `<SearchResults />` component, passed the new `bookings` state variable.

`CYF-Hotel-React-App(assignment)`

``` const [bookings, setBookings] = useState("FakeBookings")
```

Now, useState is carrying the current value of bookings that we are getting from the file FakeBookings

The data is already saved in the file & it's static data. What will happen if we want to get data from an API?So to get data from an API we need to fetch the data. That can be done using useEffect the hook.

useState also takes the function version. The function will run only once when the component renders.