Using useEffect, Effectively
React Hooks: useEffect
As I continue to sharpen my JavaScript skills, along with developing my React skills , I have continuously heard that the the use of React Hooks as something almost all of potential employers look for. React Hooks allows you to always use functional components rather than class components , making your components cleaner and more efficient. I will go over the useEffect hook what it does and why it is important to use it.
What is useEffect hook?
useEffect — as the name suggests — is a hook to perform arbitrary side effects during a life of a component. useEffect tells your component to do something after every render. It is basically a hook replacement for the lifecycle methods componentDidMount, componentDidUpdate and componentWillUnmount. It allows you to execute lifecycle tasks without a need for a class component. So you can now make side effects inside a functional component. useEffect runs after every render making it is like a componentDidMount, componentDidUpdate, and componentWillUnMount all in one.
When to use the useEffect hook
We can use the useEffect hook to do various operations that aren’t allowed inside the main body of the function component, which is anything outside the rendering phase.The useEffect hook is usually used to execute mutations, setting timers, and other side effects. The useEffect hook is used to execute code that needs happens during lifecycle of the component instead of on specific user interactions or DOM events. The useEffect hook can be fetch data when a component mounts, how to run code when state changes or when a prop changes.
useEffect makes code cleaner and more efficient, getting the ability to use all three lifecycle methods by using one hook, can be a real game changer while writing React.