I do not understand the need to use useEffect for cases where I want to do things, for example, before rendering. For example, in the code below, I want to fill the data with information, for example, by receiving from an API. Now the difference of the following code:
const Product_List = (props) => {
const [data, setData] = useState();
getData((response)=> setData(response));
return(
<FlatList
data={data}
/>
)
}
With the following code:
const Product_List = (props) => {
const [data, setData] = useState();
useEffect(() => {
getData((response)=> setData(response));
}, []);
return(
<FlatList
data={data}
/>
)
}
In other words, different of this code:
class Product_List extends Component{
constructor(props) {
this.state = {
data: []
}
getData((response)=> this.setState({data: response}));
}
render(){
return(
<FlatList
data={data}
/>
)
}
}
With the following code:
class Product_List extends Component{
constructor(props) {
this.state = {
data: []
}
}
componentDidMount(){
getData((response)=> this.setState({data: response}));
}
render(){
return(
<FlatList
data={data}
/>
)
}
}
Functions which make up Function Components get called every time the component is rendered.
useEffect puts some code aside so it only runs when one of the dependencies changes.
In your second example, you have a dependency list of [] so it only runs when the component is first rendered.
In your first example, you call getData every time the component is rendered. So it renders, you call getData, which calls setData which triggers a render, so you call getData and you have an infinite loop.
Your Class Component code is not equivalent.
When your console.log is outside of useEffect, it runs during the "render phase"
“Render phase” Pure and has no side effects. May be paused, aborted or restarted by React.
When you use it inside of useEffect, it runs after the "render phase", or during the "commit phase".
“Commit phase” Can work with DOM, run side effects, schedule updates.
https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
so it would not be wise to do side effects outside useEffect or componentDidMount, as React's behavior isn't always a we expect.