First Post alert!
Writing this post by a 2yr old javascript developer! After learning react concepts like class(who doesn't belongs to javascript community) Component, state, props, router, redux, context, PureComponent blah blahh!suddenly dan be like hooray!! we are introducing react hooks.
developers like wth is this man!😳 after learning that's pretty nice!😊
yes! hooks are just normal functions which perform side effects for your Application.hooks reduced a way more of our abstraction for the react components and also we can reuse some of the common logic that we are using across all the class components into a single custom hook.
Lets see one of them
useEffect one of the most used built in hook. which will be called after your component mounts and perform side effect for your page for sequence of renders depending on the dependency of array that you are passing as the second argument.
Example
useEffect(() => {
fetchApiData()
}, []) // here if you can see the second argument which is an empty array means it can only be called only once in your component.
useEffect(() => {
someBusinessLogic(propValue)
}, [propValue]) // consider propValue is a prop passed from the parent component which may or may not can change. as you guessed this useEffect will be called whenever ur parent component passes a different value compared to the previous one.
You can use as much of useEffect in your component depending on the useCase of your Component! Comparing this useEffect with componentDidMount or any other LifeCycle method is absolutely Wrong!
To resolve some common developer problems to get through this.
I have created a simple custom hooks useComponentDidMount,
useComponentUnmount which will make you to think as of the plain old react lifecyle componentDidMount and componentWillUnMount.
NOTE: though the name suggest useComponentDidMount... it just an abstraction or a wrapper to the useEffect.
Some Sample Usage
useComponentDidMount(() => {
yourSideEffectLogic()
subscriptions()
})
useComponentUnMount(() => {
unsubscriptions()
})
From the above as you can see there are no such dependency passing you need to worry about and both the effects follow the exact same pattern and moreover its not messy :).
Click Here for usage Instructions for the above NPM Package.
Expecting some valuable inputs and advices✋ from the readersas this is my first post!
Thank you for spending your valuable time!
Noob Programmer.
Top comments (0)