Named useEffect function
Prakash Ravichandran
SDE-II @ Comcast | Front-End Development | React | Next.js | JavaScript | TypeScript | Open-Source
Using the Named useEffect function provides you insights in debugging, better readability, purpose of an Effect function.
The reasons i have investigated is as follows:
1. Improves debugging by showing the named function in the stack trace when an useEffect function throws an error.
2. Helps other programmers better readability of the useEffect function.
3. One useEffect is for only one purpose.
Reference: Stackblitz Implementation
Below showing an example of making an api using Named useEffect function.
领英推荐
useEffect(
function makeApiCallAfterMount() {
async function fetchData() {
const res = await fetch('https://jsonplaceholder.typicode.com/todos/');
const data = await res.json();
setData(data);
}
x = data; /* Reference Error in stack trace */
fetchData();
},
[ ]
);
Stack Trace Image for Named useEffect Function: This helps which function causes the issue along with the stack trace line no.
The useEffect function with arrow function syntax:
useEffect(() => {
const fetchData = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/todos/');
const data = await res.json();
setData(data);
};
x = data; /* Reference Error in stack trace */
fetchData();
},
[ ]
);
Stack Trace Image for Arrow Syntax useEffect Function: Stack trace error provides you only the line no which causes the issue.
Do you have any other suggestions of using Named useEffect ?
Please do share your views.