I started learning React Router V6 and got to the topic of Loaders. So, it sounds like Loaders are used to load data before a component is rendered and useEffect loads the component first and the data comes after. (Correct me if I’m wrong)
What are Pro and Cons of each?
What are examples of when a Loader would be better, a good option, or helpful to use instead of useEffect?
What are examples of when useEffect would be better, a good option, or helpful to use instead of a Loader?
Can they be used together? What are some examples?
What about CRUD operations? Would one option best suit an operation more than another? Any examples?
Would appreciate any info you can give me. Thanks!
I don’t have a firm answer, but want to give my thoughts. I’m definitely happy to be picked up and corrected on anything.
There have been some updates to the React documentation that you might not be aware of. They’re asking people to use the useEffect hook with more caution. Read more here useEffect • React
My understanding is that useEffect only updates the react dom when the data comes from an external source.
Note you should really only use the useEffect hook if you’re dealing with external sources.
When it comes to react routers loader package. They say
“Use when requiring the component for a Route , and the component will only be loaded when the route is rendered.” react-router-loader - npm
I think it is a form of lazy loading technique to render your components as and when a user clicks on a route.
My take on it is that components are local, so there is a separation of concerns. You can use useEffect for external calls and use loaders for local component rendering dependent on the users root.
Could be wrong, but entering into this in the spirit of discussion
Thanks for sharing the docs on why I might not need useEffect. After reading it I think im using it right. Below is an example
useEffect(() => {
const fetchItem = async () => {
try {
let response = await axios.get('API');
setItem(response.data);
} catch (error) {
console.log(error);
//If the post isn't found then go to my catch all errors page
navigate("*")
}
}
fetchItem()
//This function isn't in useEffect since I have to call it somewhere else to
fetchComments()
}, [id, fetchComments, navigate])
I still have a lot to learn about React. I’m wondering if choosing loaders over useEffect is more of a matter of preference…
I think with Loaders you are able to use elementError in your routes but I may just be doing it wrong lol