I've just created a function component which contains the expression const [state, setState] = useState()
. Now that I have access to state
and setState()
, this stateful function component is very similar to a stateful class component. I'm only aware of two differences between this component and a typical class component: when referring to the state we must use state.handle
instead of this.state.handle
, and we have easy access to the Context API outside of the render
method.
Aside from the differences that I found already, is there any difference between this stateful function component and a stateful class component? Am I incorrect in my above assertion?
To refine this question just a bit, is there anything a Class Component can do that a Function Component with Hooks can't do?
Before The Hooks:
After Hooks:
With the introduction of Hooks, we can create stateful components without using classes.
We can use functions to create stateful components.
Helpful Articles
Article 1
Article 2
As Sung M. Kim said there are 3 life-cycle hooks that is not implemented yet in react hooks.
As mentioned in the docs, getDerivedStateFromProps exists for only one purpose. It enables a component to update its internal state as the result of changes in props.
You can achieve the same using useEffect & useState hooks. useEffect accept as a second parameter an array of dependent variables to that will cause the useEffect to rerun, so you can do the following:
const [state1, changeState1] = useState(props.prop1);
useEffect(() => {
changeState1(props.prop1)
}, [props.prop1]);
componentDidCatch
getDerivedStateFromError
This hooks catch errors in the children tree except the following (docs):
Event handlers (learn more) Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks) Server side rendering Errors thrown in the error boundary itself (rather than its children)
There are a lot of differences between a function and a class, and they show up in the syntax. Furthermore, lifecycle methods in component classes are different than hooks in component functions. But the bottom line is that you aren’t missing any functionality by using function components. In fact function components with hooks are now the default way to create react components. Lots more here:
https://reactjs.org/docs/hooks-intro.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With