In last story, we made a simple count app with class component.
Today, we are gonna change that code to function component.
Let’s start 🔥🔥🔥
Step 1 Make function component
We don’t need ‘class’, ‘extends’, ‘Component’ anymore.
Delete them all and simply type ‘export default function App()’.
Now we only import React instead of React, {Component} from ‘react’
Step 2 Delete constructor and use useState
In function component, We don’t use constructor to initialize state
Instead, we can simply use useState hook that returns a stateful value, and a function to update it.
Before you use hooks in function component there are some rules to remember
1. Only call hooks at the top level (Don’t call hooks inside loops, conditions, or nested functions)
2. Only call hooks from react functions (not from general functions)
Step 3 Change tick function
Now we can change count state with setCount.
The code above means increase count state by 1 from current count state
Do not write like this setCount(count +1). because useState hook works asynchronously this can make bugs sometimes.
Step 4 Replace lifecycle method to useEffect hook
The function passed to useEffect will run after the render is committed to the screen.
Using useEffect with empty array means it does not depend on any variables (no dependency).
So the code above will simply run function after App component is mounted and then will not be updated because there is no dependency).
We can run function (unsubscribe) before App component will mount by writing return () => (function) in the end.
Also you may noticed that we don’t need to use ‘this’ keyword anymore.😍
Step 5 Delete render method
Finally it’s time to delete render method!!!
Then replace this.state.count to count
If you guys follow this steps the count app will work exactly same way
Complete
As you can see, function component is a lot more simple compared to class component. So i prefer to use function component.
But, to understand other person’s code or code that was made few years ago (when react hook doesn’t exist), we also need to know class component as well.
If we can use both type of component easily, we can take one step further to the next level.
Thank you guys for reading my article.
Welcome every comment!!!
reference: https://reactjs.org/