Introduction

Hi everyone, surely everyone among React Developers knows about a react-hook, a very special hook, a concept that many people discuss and even in the title of the blog post, it already reveals the name of that hook, which is none other than useEffect. And today, let's deep dive into it. Let's go!!!

useEffect is one React API, and built-in React core. According to the blog's title "best practices", normally known as practice, training with the "best" way, or using it properly, reasonably, not "stupid". With a title that sounds "only for newbies", but in this blog instead of showing cases that use useEffect in our react app, we avoid using useEffect. Ohh, why do we avoid one most popular API developed by React team? Let's research with me ❤️

Before we go to cases that needn't use useEffect. Let's have a look together at one concept that I guest any React Dev need to know. It's React-lifecycle concept.

I have "stolen" one diagram that represents the lifecycle in React here

Untitled

This diagram is designed by one member in React Dev team reference

We can easily see the progress of Render and Commit phase in the left column and inside each progress, they also describe the event's action.

It will take a lot of time to explain behind the scene each step, so I design a "lite" diagram to make lifecycle's diagram simplify

Untitled

Component just like us. Having birth stage (componentDidMount), growing stage (componentDidUpdate), and the last one is "dead" (componentWillUnmount). So, do we gumshoe, and catch the mutation component progress? Fortunately, the react-hook which we mention in this blog can do. Is this hook potential and powerful, right?

In addition to the inherent benefit that this hook brings, it still has some latent surrounding app's performance. Effects are an escape hatch from the React paradigm, and I call "black sheep". They let you “step outside” of React and synchronize your components with some external system like a non-React widget, network, or the browser DOM. Read more

Coming back to the main issue, here we will mention some ways we can avoid useEffect out of our react app that I feel is effective and particular to me.

Updating state based on props or state

Suppose you have a component with two state variables: firstName and lastName. You want to calculate a fullName from them by concatenating them. Moreover, you’d like fullName to update whenever firstName or lastName change. Your first instinct might be to add a fullName state variable and update it in an Effect: