React useEffect() Hook

Michael Abe
2 min readOct 14, 2021

Probably the most important aspect of a web based app for the end user is interacting with the app itself. Interacting with the web app often depends on the user clicking something on the page, followed by and event occurring. While this is obviously a great way to make “something happen”, since it is ultimately dependent on the user interacting with something on the page to generate a result, the act itself is dependent on the page loading and rendering that point for the user to interact with. As a developer, you may want some side-effect events to happen without direct interaction on the screen (an alert is one example) or maybe a keypress to trigger an event instead of a mouse click.

The main way that we control the-side effect aspect of react component based coding while using class components is through the implementation of lifecycle methods, specifically ‘componentDidMount’, ‘componentDidUpdate’, and ‘componentWillUnmout’. These three methods are essentially combined in React functional components by using the ‘useEffect’ hook.

What does ‘useEffect’ actually do? Simply put, use effect lets you control the side-effects independently letting you seperate the rendering and side-effect from each other. There are many times that you don’t necessarily want every side-effect to happen upon each new render that React preforms.

The way that the ‘useEffect’ function is written accepts two arguments. The first argument is the callback function that you want to be executed, the second argument is an array that you want the calling of the function to be dependent on. This array is optional if you don’t include it, your callback function will be called after every rerendering of your component, if you pass an empty array ‘[]’ as the second argument, your callback function will be once after the first rendering of the component.

Simply put, if you want to control the call of certain functions that are side-effects like fetches, keypress event establishment, or anything else, the way to do it with a functional component in React is by implementing the ‘useEffect’ hook. It combines the lifecycle events that a class component typically employs and is versatile enough to be catered to many different needs.

--

--