Understanding React Hooks
A milestone achievement, 100 days into the job and loving every minute of it. Over the past 2 weeks, I've been working on the corporate website updating the content and making sure the design and UX was consistent with our brand changes. Security Risk -> Software Risk
I also learnt how to do deployments on the backend to our Google Cloud Platform, build pipelines for CI/CD.
100 days of code
Coincidentally, my domain host subscription expired while GatsbyJS had a new upgrade from v2 to v3. So I took the time to revamp my the blog while I was waiting for the domain registra changes to take place. Moving out from En Technologies to Google Workspace was a breeze, it was essentially moving away from cPanel Interface to the Google platform. Since I'm already heavily invested into the suite of Google services, I might as well control everything together and at a cheaper rate with a real 24/7 support.
Understanding a useEffect Hook
This week, while I slowly eased back into actual development. I went through my pull requests with my Senior Dev Nur Shadah who is a really good mentor by the way, As a new Frontend developer, understanding how the various Hooks work can be a little challenging. As someone who learnt ReactJS from reading stackoverflow, medium and dev.to articles, React Hooks can be really abstract, basic Hooks like useState
is pretty simple to understand because what it does is store the value instead of having you write boilerplate code for componentDidMount , componentWillUnmount and componentDidUpdate. But understanding these 3 building blocks will help you understand how the useEffect works. If we have the following code,
This will re-render the component infinitely. Which in most cases, you do not want that to happen or you will face performance issues. Because it works like componentDidMount only.
Now by adding an empty dependency []
, it will check for componentDidMount and if you were to add a value inside the dependency.
useEffect
will re-render only when the value of hook
is updated. The dependency []
will become a componentDidUpdate of sorts, I could be wrong but this is how I think it works. Now what happened to componentWillUnmount ?
useEffect
has an optional statement you can use, by using return
. Based on the React documentation, the logic behind is simple because componentDidMount and componentWillUnmount is part of the same effect.