Reputation: 321
I wonder if someone can help... I've have the below template/boilerplate I'm working on for a personal learning project (lockdown ay!)
The below code loads fine...however I added a console.log so I could see the data pulling through ok and I've noticed every 10 seconds (the refresh rate I set for the fetch) it logs the data 3 times every times (causing unsightly rerenders when I put in graphs or visuals etc.)
Can someone help my understand why its rerendering 3 times each time?
import React, {useState,useEffect} from 'react';
import AppContext from './context'
function App() {
const [state,setState] = useState([])
const [isLoading,setIsLoading] = useState(true)
const [isError,setIsError] = useState(false)
const appRefreshRate = 10000
useEffect(() => {
let interval
const fetchData = async () => {
setIsLoading(true)
try {
const res = await fetch(`myapiaddress`, {
method: 'POST',
mode: 'cors',
body: JSON.stringify({
client: 'xxx',
}),
headers: {
'content-type': 'application/json',
credentials: 'include'
}
})
res.json().then(res => {
let data = JSON.parse(res)
setState({
data1: data.recordsets[0],
})
})
} catch (error) {
setIsError(true)
}
setIsLoading(false)
}
fetchData()
interval = setInterval(fetchData, appRefreshRate)
return () => clearInterval(interval)
}, [appRefreshRate])
const appContext = {
state: state
}
console.log(state)
return (
<AppContext.Provider value={appContext}>
Test
</AppContext.Provider>
);
}
export default App;
Upvotes: 1
Views: 493
Reputation: 743
The component App
is a function that will get called every time it needs to be rendered.
And every time this function gets called, the code inside will be executed, resulting in this case in
console.log(state)
being called.
Many things can trigger a so-called render ( executing the function App()
)
One of them is a change in the value of variables defined using the useState
hook.
Whenever you call a setter function that changes the value of the underlying variable, the component needs to be rendered again as changes in those values might result in different visuals, or status in the app.
In your case you have 3 instances where you modify the state:
setIsLoading(true) // triggers a render
setState({ data1: data.recordsets[0] }) // triggers a render
setIsLoading(false) // triggers a render
That'll call App()
3 times, each time with the updated values in the state variables and therefore run your console.log(state)
instruction.
Upvotes: 2