React Project Best Practices
Code Snippets
Functional components are far more efficient than class based components. There is also less code that is needed to be written to achieve the same goal.
Execute code on mount and unmount in functional components
Answer is useEffect hook.
If we pass an empty array as the second argument, it tells useEffect to fire on component load. This is the only time it will fire.
Functional components are far more efficient than class based components. There is also less code that is needed to be written to achieve the same goal.
Execute code on mount and unmount in functional components
Answer is useEffect hook.
If we pass an empty array as the second argument, it tells useEffect to fire on component load. This is the only time it will fire.
import React, { useEffect } from 'react';
const ComponentExample = () => {
useEffect(() => {
// Anything here is fired on component mount
}, []);
};
const ComponentExample2 = () => {
useEffect(() => () => {
// Anything here is fired on component unmount
}, []);
};
const ComponentExample3 = () => {
useEffect(() => {
// Anything in here is fired on component mount.
return () => {
// Anything in here is fired on component unmount.
};
}, []);
};
Now what about the dependency array passed to useEffect? We know from the documentation that:
- It’s optional. If you don’t specify it, the effect runs after each render.
- If it’s empty ([]), the effect runs once, after the initial render.
- It must — or as we’ll see later, should — contain the list of values used in the effect. The effect runs after any of these values changes (and after the initial render).
- The array of dependencies is not passed as argument to the effect function.
The last point is important. It means that the array plays no direct role in ensuring that the effect runs with fresh values (the effect always runs with the value at the time the component is rendered, as we’ve just seen). The array only controls when the effect runs.
Stop user from closing browser Tab/Window
window.addEventListener('beforeunload', (ev) =>{ev.preventDefault();return ev.returnValue = 'Are you sure you want to close?';});
Use Debouncing to handle multiple event fires on any action
Ref - https://blog.logrocket.com/how-and-when-to-debounce-or-throttle-in-react/#:~:text=Its%20usage%20is%20similar%20to,object%20as%20the%20third%20argument.Why prefer connect over useSelector/useDispatch hook
https://www.samdawson.dev/article/react-redux-use-selector-vs-connect
No comments:
Post a Comment