Migrated Class Component to React Hooks.

kosa3
2 min readMay 12, 2019

--

「react hooks」の画像検索結果

Since I studied React hooks, I made a simple application compared to Class Component.

About React Hooks

React 16.8 introduced a brand-new feature to React: “React Hooks”.
It allow you to build your entire React app with functional components only.

Advantages of using Hooks
・Less Code and not conscious of this, because it is not a Class.
・Classes can be confusing and could easily be used incorrectly.
・Easy to migrate. because It can be reused by giving a state.

The Working Example

sample app demo

It is an application that displays the name and weather of the city, the strength of the wind from the data of the API of the weather forecast and enter the city name.

Prerequisite

・Init React Project
・OpenWeatherMap APIKEY (https://openweathermap.org/api)

First, Create React Project by `create-react-app` command.
`create-react-app` is pre-installed.

$ npm install -g create-react-app
$ npx create-react-app sample-hooks

Next, sign up OpenWeatherMap, and get your APIKEY.

Let’s look at the code implemented in Class Component and Functional Component

Class Component

First, I create an App Class and inherit React.Component to create Class Component. Second, Initialize state in constructor.
Third, Retrieve data from API and update state using ComponentDidMount of React lifecycle.
You can see that Tokyo data is displayed on the initial screen.
Also, enter the city name and press submit to display the weather information of the entered city.

Functional Component (Hooks)

First, I create an App Function. Second, Initialize state in useState.
Third, Retrieve data from API and update state using useEffect of React hooks.
useEffect is a function of hooks API and plays the role of componentDidMount. We add state data depending on the second argument in useEffect, because re-rendering may occur when unintended.

Summary

I migrated to React Hooks, but it took a little time to get used to it, but I was able to make the same operation.
React Hooks has many other features `useReducer` `useMemo` `useContext`…
Next, I would like to compare and verify Redux and Hooks.
* I always ready to loading feature in source code.

https://reactjs.org/docs/hooks-reference.html

--

--

No responses yet