Easy to Learn React Hooks. Take useEffect() as an example | by Sabesan Sathananthan

FRONT END

Take useEffect() as an example

Photo by Grant Durr on Unsplash

I already wrote about React best practices. I have mentioned that React hooks write stateful functional components. Nowadays, Most of the React frameworks such as react-i18next, Material-UI, and etc are encouraged to use React hooks. However, recently I have come to realize that React hooks are very useful. React hooks are introduced after the React v16.08. Here I am going to describe React hooks very simply and easily. This is my 34th Medium article.

In the past, there was only one set of React API, now there are two sets: class API and function-based hooks API. Any component can be written by a class or a hook. Here is how to write the class.

Let’s look at the way the hook is written, that is, the function.

These two ways of writing have exactly the same effect. Beginners will naturally ask: “Which API should I use?”

The official recommendation is to use hooks (functions) instead of classes. Because hooks are more concise and less code, they are “lighter” to use, while classes are “heavier”. Moreover, hooks are functions, which are more in line with the functional nature of React.

The following is a comparison of the amount of code for class components (left) and functional components (right). For complex components, the difference is even more.

However, the flexibility of hooks is too great for beginners to understand. Many people have little knowledge and can easily write messy and unmaintainable code. It would be better to use classes. Because classes have many mandatory grammatical constraints, it is not easy to mess up.

Strictly speaking, there is a difference between class components and functional components. Different writing methods represent different programming methodologies.

A class is an encapsulation of data and logic. In other words, the state and operation method of the component are encapsulated together. If you choose the type of writing, you should write related data and operations in the same class.

https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/Function_machine2.svg/1200px-Function_machine2.svg.png

Generally speaking, functions should only do one thing, which is to return a value. If you have multiple operations, each operation should be written as a separate function. Moreover, the state of the data should be separated from the operation method. According to this philosophy, React’s functional components should only do one thing: return the HTML code of the component, and have no other functions.

Take the below functional component as an example.

This function only does one thing, which is to return the HTML code of the component based on the input parameters. This kind of function that only performs simple data calculation (conversion) is called “pure function” in functional programming.

Seeing this, you may have a question: If pure functions can only perform data calculations, where should those operations that do not involve calculations (such as generating logs, storing data, changing application status, etc.) be written?

https://functionalprogrammingcsharp.com/images/posts/pure-functions.jpg

Functional programming that calculates those operations without relating to data are called “secondary effects” (Side Effect). If a function directly contains operations that produce side effects, it is no longer a pure function, and we call it an impure function.

Only through indirect means (that is, through other function calls) inside a pure function can it contain side effects.

After talking for a long time, what exactly is a hook? In a word, the hook is the side effect solution of the React functional component, which is used to introduce side effects to the functional component. The body of the function component should only be used to return the HTML code of the component, and all other operations (side effects) must be introduced through hooks.

Since there are so many side effects, there are many kinds of hooks. React provides special hooks for many common operations (side effects).

  • useState(): Save state
  • useContext(): Save context
  • useRef(): Save reference

These hooks above, are the introduction of a specific side effect and useEffect() is a common side effect of the hook. You can use it when you can’t find the corresponding hook. In fact, as you can see from the name, it is directly related to side effects.

https://dev.to/swapnadeepmohapatra/useeffect-react-hooks-25fb

useEffect() is a function itself, provided by the React framework, and can be called inside the functional component.

For example, we hope that after the component is loaded, the page title (document.title) will change accordingly. Then, the operation of changing the title of the webpage is a side effect of the component, which useEffect() implemented.

In the above example, useEffect() the parameter is a function, which is the side effect to be completed (change the page title). After the component is loaded, React will execute this function.

The role of useEffect() is to specify a side effect function, which is automatically executed every time the component is rendered. After the component is first loaded in the web page DOM, the side effect function will also be executed.

Sometimes, we don’t want useEffect() to execute every rendering. At this time, we can use its second parameter to use an array to specify the dependencies of the side effect function. Only when the dependencies change, the rendering will be performed again.

In the above example, useEffect() the second parameter is an array that specifies the dependency (props.name) of the first parameter (side effect function ). Only when the variable changes, the side effect function will be executed.

If the second parameter is an empty array, it means that the side effect parameter does not have any dependencies. Therefore, the side effect function will only be executed once after the component is loaded into the DOM, and the subsequent component will be re-rendered and will not be executed again. This is reasonable because the side effects do not depend on any variables, so no matter how those variables change, the execution result of the side effect function will not change, so it is enough to run it once.

As long as it is a side effect, you can use the useEffect() introduction. Its common uses are as follows.

  • Data fetching
  • Event monitoring or subscription (setting up a subscription)
  • Change the DOM (changing the DOM)
  • Output log (logging)

The following is an example of getting data from a remote server.

In the above example, it is useState()used to generate a state variable ( data) to save the acquired data; useEffect()inside the side effect function, there is an async function to asynchronously acquire data from the server. After getting the data, use the setData()trigger component to re-render.

Since data acquisition only needs to be executed once, useEffect()the second parameter of the above example is an empty array.

Side effects occur as components are loaded, so when components are unloaded, these side effects may need to be cleaned up.

useEffect() allows to return a function, which is executed when the component is unloaded to clean up side effects. If you don’t need to clean up the side effects of useEffect() you don’t need to return any value.

useEffect(() => {
const subscription = props.source.subscribe();
return () => {
subscription.unsubscribe();
};
}, [props.source]);

In the above example, useEffect() an event is subscribed when the component is loaded, and a cleanup function is returned, and the subscription is canceled when the component is unloaded.

In actual use, since the side effect function executes every rendering by default, the cleaning function will not only be executed once when the component is unloaded but also once before the side effect function is re-executed to clean up the side effects of the previous rendering effect.

There is one thing to pay attention to when using useEffect(). If there are multiple side effects, multiple useEffect() should be called instead of being combined and written together.

The above example is wrong. There are two timers in the side effect function. They are not related. In fact, they are two unrelated side effects and should not be written together. The correct way is to write them separately into two useEffect().

Most of my social media friends suggest to me to write about React hooks because they want to understand them easily. Here I have written about the hooks with basic Javascript concepts and took the useEffect() as an example.

Happy New Year 🎉

Happy coding 😎

Gain Access to Expert View — Subscribe to DDI Intel

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: