I know the conventional way when using hooks is to fetch the data using the useEffect hook. But why can't I just call axios in the functional component instead of a hook and then set the data.
Basically, I am asking what is wrong with doing this:
const [users, setUsers] = useState(null);
axios.get("some api call")
.then(res => setUsers(res.data))
Here, I do not use useEffect, what could go wrong?
Making a request and changing the state on render like that will cause the component to re-render forever.
Every time the component renders, e.g. due to props changing or due to hooks changing, that axios.get request gets called. When it gets a response, it will update the state. Then, because the state has changed, the component re-renders, and axios.get is called again. And the state changes again, and the request is made again, forever.
Prefer useEffect(() => code... , []).
That said, you can also do it while avoiding an infinite loop but it's a very bad practice and I don't recommend it.
Yes, you will have a re-render but you won't have an infinite loop. Use useState's lazy init function.
const [users, getUsers] = useState(() => {
axios.get("some api call")
.then(res => getUsers(res.data))
});
Best practice is :
const [users,getUsers]= useState();
useEffect ( () => {
axios.get("some api call")
.then(res=>getUsers(res.data))
}, []);
Related
I have a state, that I only want to change when a certain funcitonal component is initialised. So I intend to do somethin like this:
export default function SalesFeedPage(){
const {salesFeed} = useSelector((state) => state.feedReducer);
const dispatch = useDispatch();
// i want to do sth like this
// useEffect(() => dispatch(loadSalesFeed()), []);
// or
// dispatch(loadSalesFeed());
return (
<div>
hello
{salesFeed}
</div>
)
}
This doesn't work since it infinitely re-renders the SalesFeedPage.
Is there a way to achieve what I want in a funcitonal component?
Just keeping the first useEffect should work, but make sure to only return cleanup functions inside of your useEffect, not your dispatch return value. Like so,
useEffect(() => { dispatch(loadSalesFeed()) }, [])
You have to use,
useEffect(() => dispatch(loadSalesFeed()), [])
if you use Dispatch outside the useEffect without dependency array, your component continuously getting re rendering. That because ,when you component mounting your dispatch function get called, so your redux state get changed, then again your component get rendered. Then your dispatched is called again. Then this make your component get render again. This lead to infinite rendering cycle.
Hope this help to you!
Let's say I have this simple dummy component:
const Component = () => {
const [state, setState] = useState(1);
setState(1);
return <div>Component</div>
}
In this code, I update the state to the same value as before directly in the component body. But, this causes too many re-renders even if the value stayed the same.
And as I know, in React.useState, if a state value was updated to the same value as before - React won't re-render the component. So why is it happening here?
However, if I try to do something simillar with useEffect and not directly in the component body:
const Component = () => {
const [state, setState] = useState(1);
useEffect(()=>{
setState(1);
},[state])
return <div>Component</div>
}
This is not causing any infinte loop and goes exactly according to the rule that React won't re-render the component if the state stayed the same.
So my question is: Why is it causing an infinte loop when I do it directly in the component body and in the useEffect it doesn't?
If someone has some "behind the sences" explanation for this, I would be very grateful!
TL;DR
The first example is an unintentional side-effect and will trigger rerenders unconditionally while the second is an intentional side-effect and allows the React component lifecycle to function as expected.
Answer
I think you are conflating the "Render phase" of the component lifecycle when React invokes the component's render method to compute the diff for the next render cycle with what we commonly refer to as the "render cycle" during the "Commit phase" when React has updated the DOM.
See the component lifecycle diagram:
Note that in React function components that the entire function body is the "render" method, the function's return value is what we want flushed, or committed, to the DOM. As we all should know by now, the "render" method of a React component is to be considered a pure function without side-effects. In other words, the rendered result is a pure function of state and props.
In the first example the enqueued state update is an unintentional side-effect that is invoked outside the normal component lifecycle (i.e. mount, update, unmount).
const Component = () => {
const [state, setState] = useState(1);
setState(1); // <-- unintentional side-effect
return <div>Component</div>;
};
It's triggering a rerender during the "Render phase". The React component never got a chance to complete a render cycle so there's nothing to "diff" against or bail out of, thus the render loop occurs.
The other example the enqueued state update is an intentional side-effect. The useEffect hook runs at the end of the render cycle after the next UI change is flushed, or committed, to the DOM.
const Component = () => {
const [state, setState] = useState(1);
useEffect(() => {
setState(1); // <-- intentional side-effect
}, [state]);
return <div>Component</div>;
}
The useEffect hook is roughly the function component equivalent to the class component's componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods. It is guaranteed to run at least once when the component mounts regardless of dependencies. The effect will run once and enqueue a state update. React will "see" that the enqueued value is the same as the current state value and won't trigger a rerender.
Similarly you could use the useEffect hook and completely remove the dependency array so it's an effect that would/could fire each and every render cycle.
const Component = () => {
const [state, setState] = useState(1);
useEffect(() => {
setState(1);
});
return <div>Component</div>;
}
Again, the useEffect hook callback is guaranteed to be invoked at least once, enqueueing a state update. React will "see" the enqueued value is the same as the current state value and won't trigger a rerender.
The takeaway here is to not code unintentional and unexpected side-effects into your React components as this results in and/or leads to buggy code.
When invoking setState(1) you also trigger a re-render since that is inherently how hooks work. Here's a great explanation of the underlying mechanics:
How does React.useState triggers re-render?
Hey I've go a problem with this code.
const [itemsCart, setCart] = useState([]);
useEffect(() => {
(async function (){
const buffer = await JSON.parse(window.sessionStorage.getItem("itemsCart"))
setCart(buffer);
console.log(buffer);
console.log(itemsCart);
})()
}, []);
useEffect(() => {
window.sessionStorage.setItem("itemsCart", JSON.stringify(itemsCart));
}, [itemsCart]);
The buffer gets the data, the state variable dosen't. I assume there must be a problem with synchronization however I'm not able to fix that.
The output:
here
This happens because react will wait until all script in useEffect is called and after that, setState will trigger rerender. Because there can be multiple setStates and we want to rerender it only once. That means, you are logging old value in console.log(itemsCart) before its actually there after rerender.
You can logi it with second useEffect before updating sessionStorage and you will see, that state is changed. Or you can create new useEffect for this
useEffect(()=>{
console.log(itemsCart)
},[itemsCart]);
this works:
const [itemsCart, setCart] = useState(JSON.parse(window.localStorage.getItem("itemsCart")));
useEffect(() => {
console.log(itemsCart);
window.localStorage.setItem("itemsCart", JSON.stringify(itemsCart));
}, [itemsCart]);
To run the second useEffect(), itemsCart needs to be modified before via useState(). I can't see in your first useEffect() when you call setItemsCart().
This question is not correct and the approach to solve the problem is not correct as well(whatever problem you are trying to solve).
React has different design.
You are trying to get the items and then set them once you get it using useEffect.
The best approach would be to pass your array as a prop from higher order component and then use your useEffect once it has been triggered by dependencies(passed prop)
Make useEffect hook run before rendering the component
I have an async function that fetches some data from an API. Since I need that data to properly load my component I decided to fetch the data in the useEffect and then store it in a useState what works just fine. However, if I try to console log it, it just shows its initial state what technically would mean it's still unset or that the console log runs before assigning the useState.
Thanks for your help in advance.
const [categories, setCategories] = useState([])
useEffect(() => {
fetchListProductCats().then(function(result){
setCategories(result.data)
})
console.log(categories) // returns -> []
}, []);
if(!categories.length){
return "loading"
}
async function with Promise, make sure you know what it means.
The console.log line in this code always runs before the Promise resolved.
If you want to observe the changing of categories, use another useEffect:
useEffect(() => {
console.log(categories);
}, [categories]);
Your state is already updated with data you wanted its showing categories with it's initial values because you have rendered useEffect with no dependancies.
And it is consoled befored being updated.
Try using below code snippets to log.
useEffect(() => {
console.log(categories)
}, [categories]);
React setState is async. It won't update immediately after calling the function. It will go through a re-rendering process first to update the user interface. Once re-rendering is done, the functions provided in the useEffect hook will be called.
useEffect(()=>{
console.log(categories)
}, [categories])
I am trying to create a React Functional Component using Typescript that will get data from an API and then send that data to another component, however, I am getting an error of "Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."
Please offer any advice!
useEffect(() => {
await axios.get('https://quote-garden.herokuapp.com/api/v3/quotes/random').then((resp) => {
setQuote1(resp.data.data[0]);
});
getQuote();
}, []);
Snippet of Code Causing Error
EDIT:
Here is the entire File where the error is occurring.
import React, { useEffect, useState } from 'react';
import { Row, Col, CardGroup } from 'reactstrap';
import axios from 'axios';
import QuoteCard from './QuoteCard';
const MainQuotes = () => {
const [quote1, setQuote1] = useState();
useEffect(() => {
await axios.get('https://quote-garden.herokuapp.com/api/v3/quotes/random').then((resp) => {
setQuote1(resp.data.data[0]);
});
getQuote();
}, []);
return (
<Row>
<Col>
<CardGroup>
<QuoteCard quoteData={quote1} />
</CardGroup>
</Col>
</Row>
);
};
export default MainQuotes;
Depending on the type of quote1 (I'm assuming it's a string) update to:
const [quote1, setQuote1] = useState('')
useEffect(() => {
function fetchQuote() {
await axios.get('https://quote-garden.herokuapp.com/api/v3/quotes/random')
.then((resp) => {
setQuote1(resp.data.data[0]);
});
}
if (!quote1) {
fetchQuote();
}
}, []);
Because the response from the API is a random quote, you have to handle it based on the value of quote1. This should work because quote1 will only be updated after the component mounts (when the value is an empty string), and the following render won't update state, so useEffect won't loop infinitely.
Before the edit, I assumed the axios request was inside of the getQuote function. I have updated my answer to reflect the code you have posted.
If the API response was static, because the items in the dependency array only cause a re-render if they are changed from their current value, it only causes a re render immediately after the first state update.
Can we get your entire code please? It seems the problem is going to be with your state hook and figuring out exactly what its doing.
My guess as of now is your state hook "setQuote1" is being invoked in a way that causes a re-render, which then would invoke your useEffect() again (as useEffect runs at the end of the render cycle) and thus, calling upon your setQuote1 hook again. This repeats itself indefinitely.
useEffect() allows for dependencies and gives you the power to tell exactly when useEffect() should be invoked.
Example: useEffect(() { code here }, [WATCH SPECIFICALLY THIS AND RUN ONLY WHEN THIS UPDATES]).
When you leave the dependency array empty, you tell the hook to run whenever ANYTHING updates state. This isn't necessarily bad but in some cases you only want your useEffect() to run when a specific state updates.
Something in your application must be triggering your useEffect() hook to run when you aren't wanting it to.