If you’re a React developer who hasn’t yet learned about React hooks, now is the moment. This post will go through the useEffect React Hook in detail. It is the hook equivalent of a Swiss Army knife. It solves a variety of issues, like how to get data when a component mounts, how to run code when a state or a prop changes, how to set up timers or intervals, and so on.
A useEffect is used for pretty much anything you want to “do” in a React component that isn’t returning JSX (any type of side effect). You may also have several useEffects per component.
All of this power comes at a cost: unless you understand how it works, it may be perplexing. In this post, we’ll look at a variety of examples so that you can grasp the conceptual model and apply it to your own code.
React Hooks – What it is trying to solve?
Hooks were first introduced in React version 16.8 and are now utilized by many React projects. Hooks overcomes the problem of code repetition between components. They are written without the use of classes. This does not imply that React is abandoning classes; hooks are simply an alternative method.
React allows you to quickly create sophisticated components with stateful logic. It is difficult to separate these components since the class relies on React Lifecycle Methods. This is where React Hooks come in.
They allow you to divide a component into smaller functions. Instead of dividing code into smaller pieces based on Lifecycle methods, you may now arrange and separate code into smaller units depending on functionality.
What is useEffect Hook?
Hooks are functions that allow you to access state and other react capabilities without having to write ES6 classes. The react hooks API has a hook called useEffect. If you’re acquainted with react life cycles, the useEffect hook is the same as the componentDidMount, componentDidUpdate, and componentWillUnmount life cycle methods combined.
According to the React Hooks documentation, it was created to solve some of the issues with ES6 class component life cycle methods.
The first argument is a callback function, which is executed by default after each render. The second parameter is an optional Dependency array that instructs the Hook to callback only if the target state changes.
The Hook compares each dependency’s historical and present states. If the two values do not match, the Hook invokes the callback specified in the first parameter. Dependency arrays alter the usual callback behavior and guarantee that the Hook ignores all other components in the component scope.
To save a message, I’m using React useState in the code sample above. After that, I take my message state variable and print it on the screen. However, I now want to useEffect to modify the message a second after the component has been mounted.
I’ve inserted my effect behind the useState line after importing useEffect from the React framework. The first parameter to useEffect is a function. When this function handler is executed, it will take care of any side effects you provide. The function is a callback function that is called when one of the React component lifecycle events occurs.
When to use it?
The useEffect hook may be useful in a variety of situations. The following are the most crucial:
- We can change this parameter from the client side when we wish to fetch data depending on a supplied argument. It will be recalled after the parameter has been updated with fresh data.
- If we want to retrieve data from an API endpoint and display it on the client-side. When our component renders, the function or handler given to the useEffect hook is executed, and data in the component states are retrieved. These statuses are then employed in user interface components.
- When your component relies on data from the outside world and we can’t ensure that data will arrive, we should useEffect (maybe the server is down there). Rather than throwing problems and preventing other components from being displayed, place them in the useEffect hook.
If the component re-renders after the first run, it will not execute.
Whenever a component renders or re-renders, it should always be executed.
By default, the program only runs once. Afterward, if the prop values change, run:
For asynchronous activities, always use useEffect.
useEffect code blocks are obvious markers of asynchronous jobs for your fellow developers. It is possible to create asynchronous code without using useEffect, but this is not the “React method,” and it increases both the complexity and the risk of mistakes.
Using useEffect instead of writing asynchronous code that may stop the UI is a well-known technique in the React community, especially the way the React team has built it to perform a side effect.
Another advantage of utilizing it is that developers can simply review the code and immediately detect code that is run “outside the control flow,” which becomes important only after the first render cycle. Furthermore, the blocks are suitable for extraction into reusable and even more semantic custom Hooks.
Using the useEffect code, increment a number per second.
Understanding the underlying design principles and best practices of the useEffect Hook, in my view, is a critical skill to learn if you want to become a next-level React developer.
To summarise, the useEffect Hook receives a function that includes imperative, potentially effect full logic. The dependence array, which is the second parameter, can be used to influence the execution. While dealing with it, it is also necessary to write cleaning code using the return function.
Let us know in the comments if the article was helpful.