Seeking advice: Reason for maximum update depth exceed - javascript

I am new to React and GraphQL. Trying to update React state with GraphQL subscription feed but it generates the update depth error.
Here is the simplified code:
import { Subscription } from 'react-apollo';
...
function Comp() {
const [test, setTest] = useState([]);
const Sub = function() {
return (
<Subscription subscription={someStatement}>
{
result => setTest(...test, result.data);
return null;
}
</Subscription>
);
};
const Draw = function() {
return (
<div> { test.map(x => <p>{x}</p>) } </div>
);
};
return (
<div>
<Sub />
<Draw />
<div/>
);
};
export default Comp;
Regular query works fine in the app and the Subscription tag returns usable results, so I believe the problem is on the React side.
I assume the displayed code contains the source of error because commenting out the function "Sub" stops the depth error.

You see what happens is when this part renders
<Subscription subscription={someStatement}>
{
result => setTest(...test, result.data);
return null;
}
</Subscription>
setTest() is called and state is set which causes a re-render, that re-render cause the above block to re-render and setTest() is called again and the loop goes on.
Try to fetch and setTest() in your useEffect() Hook so it does not gets stuck in that re-render loop.
useEffect like
useEffect(() => {
//idk where result obj are you getting from but it is supposed to be
//like this
setTest(...test, result.data);
}, [test] )
Component Like
<Subscription subscription={someStatement} />

Related

Component is loading twice [duplicate]

I don't know why my React component is rendering twice. So I am pulling a phone number from params and saving it to state so I can search through Firestore. Everything seems to be working fine except it renders twice... The first one renders the phone number and zero points. The second time it renders all the data is displayed correctly. Can someone guide me to the solution.
class Update extends Component {
constructor(props) {
super(props);
const { match } = this.props;
this.state = {
phoneNumber: match.params.phoneNumber,
points: 0,
error: ''
}
}
getPoints = () => {
firebase.auth().onAuthStateChanged((user) => {
if(user) {
const docRef = database.collection('users').doc(user.uid).collection('customers').doc(this.state.phoneNumber);
docRef.get().then((doc) => {
if (doc.exists) {
const points = doc.data().points;
this.setState(() => ({ points }));
console.log(points);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
const error = 'This phone number is not registered yet...'
this.setState(() => ({ error }));
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
} else {
history.push('/')
}
});
}
componentDidMount() {
if(this.state.phoneNumber) {
this.getPoints();
} else {
return null;
}
}
render() {
return (
<div>
<div>
<p>{this.state.phoneNumber} has {this.state.points} points...</p>
<p>Would you like to redeem or add points?</p>
</div>
<div>
<button>Redeem Points</button>
<button>Add Points</button>
</div>
</div>
);
}
}
export default Update;
You are running your app in strict mode. Go to index.js and comment strict mode tag. You will find a single render.
This happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.
From the docs:
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:...
^ In this case the render function.
Official documentation of what might cause re-rendering when using React.StrictMode:
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
This is because of React Strict Mode code.
Remove -> React.StrictMode, from ReactDOM.render code.
Will render 2 times on every re-render:
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Will render 1 time:
ReactDOM.render(
<>
<App />
</>,
document.getElementById('root')
);
React is rendering the component before getPoints finishing the asynchronous operation.
So the first render shows the initial state for points which is 0, then componentDidMount is called and triggers the async operation.
When the async operation is done and the state been updated, another render is triggered with the new data.
If you want, you can show a loader or an indicator that the data is being fetched and is not ready yet to display with conditional rendering.
Just add another Boolean key like isFetching, set it to true when you call the server and set it to false when the data is received.
Your render can look something like this:
render() {
const { isFetching } = this.state;
return (
<div>
{isFetching ? (
<div>Loading...</div>
) : (
<div>
<p>
{this.state.phoneNumber} has {this.state.points} points...
</p>
<p>Would you like to redeem or add points?</p>
<div>
<button>Redeem Points</button>
<button>Add Points</button>
</div>
</div>
)}
</div>
);
}
React.StrictMode, makes it render twice, so that we do not put side effects in following locations
constructor
componentWillMount (or UNSAFE_componentWillMount)
componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)
componentWillUpdate (or UNSAFE_componentWillUpdate)
getDerivedStateFromProps
shouldComponentUpdate
render
setState updater functions (the first argument)
All these methods are called more than once, so it is important to avoid having side-effects in them. If we ignore this principle it is likely to end up with inconsistent state issues and memory leaks.
React.StrictMode cannot spot side-effects at once, but it can help us find them by intentionally invoking twice some key functions.
These functions are:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method
Function component bodies
State updater functions (the first argument to setState)
Functions passed to useState, useMemo, or useReducer
This behaviour definitely has some performance impact, but we should not worry since it takes place only in development and not in production.
credit: https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/
it is done intentionally by react to avoid this
remove
<React.StrictMode> </React.StrictMode>
from index.js
I worked around this by providing a custom hook. Put the hook below into your code, then:
// instead of this:
useEffect( ()=> {
console.log('my effect is running');
return () => console.log('my effect is destroying');
}, []);
// do this:
useEffectOnce( ()=> {
console.log('my effect is running');
return () => console.log('my effect is destroying');
});
Here is the code for the hook:
export const useEffectOnce = ( effect => {
const destroyFunc = useRef();
const calledOnce = useRef(false);
const renderAfterCalled = useRef(false);
if (calledOnce.current) {
renderAfterCalled.current = true;
}
useEffect( () => {
if (calledOnce.current) {
return;
}
calledOnce.current = true;
destroyFunc.current = effect();
return ()=> {
if (!renderAfterCalled.current) {
return;
}
if (destroyFunc.current) {
destroyFunc.current();
}
};
}, []);
};
See this blog for the explanation.
Well, I have created a workaround hook for this. Check this, if it helps:
import { useEffect } from "react";
const useDevEffect = (cb, deps) => {
let ran = false;
useEffect(() => {
if (ran) return;
cb();
return () => (ran = true);
}, deps);
};
const isDev = !process.env.NODE_ENV || process.env.NODE_ENV === "development";
export const useOnceEffect = isDev ? useDevEffect : useEffect;
CodeSandbox Demo: https://github.com/akulsr0/react-18-useeffect-twice-fix
React internally monitors & manages its render cycles using its virtual dom and its diffing algorithms, so you need not worry about the number of re-renders. Let the re-renders to be managed by react. Even though the render function is getting invoked, there are sub components which doesn't gets refreshed on ui, if there is no props or state change inside it. Every setstate function call will inform react to check the diffing algorithm, and invoke the render function.
So in your case, since you have a setstate defined inside the getPoints function, it tells react to rerun the diffing process through the render function.

Understand error destroy is not a function

I don't understand, I'm trying to improve my app.js code by adding a function 'languageSetUp()' to useEffect and I find myself facing the error:
destroy is not a function. (In 'destroy()', 'destroy' is an instance
of Object)
Do you know what it is due to? And what does that mean? I do not understand where the problem is, if you can help me and especially explain to me, I thank you in advance. Thanks for any time or help offered.
After search I think it's due to 'this.props' I don't know how to replace it in a functionnal component at first I wanted to do :
if (isConnected === true && this.props && this.props.navigation) {
this.props.navigation.navigate("BottomTabNavigator");
} }
export default function App() {
Text.defaultProps = Text.defaultProps || {};
Text.defaultProps.allowFontScaling = false;
const [user, setUser] = useState({ loggedIn: false });
const state = { user, setUser };
const [loading, setLoading] = useState(true);
async function languageSetUp() {
let lang = await retrieveAppLang();
let isConnected = await userSessionActive();
if (lang.length == 2) {
i18n.changeLanguage(lang);
}
if (isConnected === true) {
this.props.navigation.navigate("BottomTabNavigator");
}
}
React.useEffect(() => {
setTimeout(() => setLoading(false), 2000);
languageSetUp();
if (loading) {
return <Splash />;
}
});
return (
<AppContext.Provider value={state}>
<NavigationContainer>
{!user.loggedIn ? (
<MainStackNavigator />
) : (
<BottomTabNavigator />
)}
</NavigationContainer>
</AppContext.Provider>
);
}
It's coming from your useEffect function. There are two problems with it:
If you return anything from useEffect, it needs to be a function. You can read more about the useEffect cleanup function here: Getting error after I put Async function in useEffect
useEffect should have a second argument, which is a dependency array. The official documentation can give you some more information about how to use it: https://reactjs.org/docs/hooks-effect.html In your case, it looks like you want to run it just once when the component mounts, so it may just be an empty array ([]) as the second parameter.
It looks like what you're trying to do is show a Splash in the event that you're in a loading state.
Instead of returning that from useEffect, you should probably return it from your component. One (simplistic) option would be:
if (loading) {
return <Splash/>;
}
return (
<AppContext.Provider value={state}>
//...
However, be aware that you have other logic errors. Right now, your loading state gets turned off after 2 seconds no matter what. You should probably wait for the return of languageSetUp and set it based on that.
Maybe something like:
React.useEffect(() => {
languageSetUp().then(() => setLoading(false))
//handle errors?
},[]);

Context Api state is not changing

im trying to call a function called deleteTask inside the Context Provider, from a component that consumes the context using the useContext hook, which deletes a certain item from an array in the state of the context provider, but when i do it, the state of the provider doesnt change at all, i try to follow the problem and the function excecutes but it seems like if it was excecuting in the scope of a copied Provider? Also tried a function to add a task and im having the same issue. I also added a function to set the active task, and i dont know why that one did work, while the others dont. I dont really know whats happening, here is the code, pleeeeease help me:
tasks-context.jsx
import React, { useState } from 'react';
import { useEffect } from 'react';
const dummyTasks = [{
task: {
text: 'hello',
},
key: 0,
isActive: false
},
{
task: {
text: 'hello 2',
},
key: 1,
isActive: false
}];
export const TasksContext = React.createContext({ });
export const TasksProvider = ( props ) => {
const [ tasks, setTasks ] = useState( dummyTasks );
const [ activeTask, setActiveTask ] = useState();
//NOT WORKING
const deleteTask = ( taskToDeleteKey ) =>{
setActiveTask( null );
setTasks( tasks.filter( task => task.key !== taskToDeleteKey ));
};
//THIS ONE WORKS (??)
const handleSelectTask = ( taskToSelect, key ) =>{
setActiveTask( taskToSelect );
const newTaskArray = tasks.map( task => {
if( task.key === key ){
task.isActive = true;
}else{
ficha.isActive = false;
}
return task;
});
setTask( newTaskArray );
};
return ( <TasksContext.Provider
value={{ tasks,
activeTask,
addTask,
deleteTask,
handleSelectTask}}>
{props.children}
</TasksContext.Provider>
);
};
the "main"
Main.jsx
import React from 'react';
import './assets/styles/gestion-style.css';
import './assets/styles/icons.css';
import { TasksProvider } from '../../Context/tasks-context';
import TaskContainer from './components/taskContainer.jsx';
function Main( props ) {
return (
<TasksProvider>
<TaskContainer />
</TasksProvider>
);
}
the task container maps the array of tasks:
TaskContainer.jsx
import React, { useContext, useEffect } from 'react';
import TaskTab from './TaskTab';
import { TasksContext } from '../../Context/tasks-context';
function TaskContainer( props ) {
const { tasks } = useContext( TasksContext );
return (
<div className="boxes" style={{ maxWidth: '100%', overflow: 'hidden' }}>
{tasks? tasks.map( taskTab=>
( <TaskTab task={taskTab.task} isActive={taskTab.isActive} key={taskTab.key} taskTabKey={taskTab.key} /> ))
:
null
}
</div>
);
}
export default TaskContainer;
And the task component from which i call the context function to delete:
TaskTab.jsx
import React, { useContext } from 'react';
import { TasksContext } from '../../Context/tasks-context';
function TaskTab( props ) {
let { task, isActive, taskTabKey } = props;
const { handleSelectTask, deleteTask } = useContext( TasksContext );
const selectTask = ()=>{
handleSelectTask( task, taskTabKey );
};
const handleDelete = () =>{
deleteTask( taskTabKey );
};
return (
<div onClick={ selectTask }>
<article className={`${task.type} ${isActive ? 'active' : null}`}>
<p className="user">{task.text}</p>
<button onClick={handleDelete}>
<i className="icon-close"></i>
</button>
</article>
</div>
);
}
export default TaskTab;
Thanks for the great question!
What is happening here is understandably confusing, and it took me a while to realize it myself.
TL;DR: handleSelectTask in the Provider is being called every time a button is clicked for deleteTask because of event propagation. handleSelectTask isn't using the state that has been modified by deleteTask, even though it's running after it, because it has closure to the initial tasks array.
Quick Solution 1
Stop the event from propagating from the delete button click to the TaskTab div click, which is probably the desired behavior.
// in TaskTab.jsx
const handleDelete = (event) => {
event.stopPropagation(); // stops event from "bubbling" up the tree
deleteTask(taskTabKey);
}
In the DOM (and emulated by React as well), events "bubble" up the tree, so that parent nodes can handle events coming from their child nodes. In the example, the <button onClick={handleDelete}> is a child of the <div onClick={selectTask}>, which means that when the click event is fired from the button, it will first call the handleDelete function like we want, but it will also call the selectTask function from the parent div afterwards, which is probably unintended. You can read more about event propagation on MDN.
Quick Solution 2
Write the state updates to use the intermediary state value at the time they are called.
// in tasks-context.jsx
const deleteTask = ( taskToDeleteKey ) => {
setActiveTask(null);
// use the function version of setting state to read the current value whenever it is run
setTasks((stateTasks) => stateTasks.filter(task => task.key !== taskToDeleteKey));
}
const handleSelectTask = ( taskToSelect, key ) =>{
setActiveTask( taskToSelect );
// updated to use the callback version of the state update
setTasks((stateTasks) => stateTasks.map( task => {
// set the correct one to active
}));
};
Using the callback version of the setTasks state update, it will actually read the value at the time the update is being applied (including and especially in the middle of an update!), which, since the handleSelectTask is called after, means that it actually sees the array that has already been modified by the deleteTask that ran first! You can read more about this callback variant of setting state in the React docs (hooks) (setState). Note that this "fix" will mean that your component will still call handleSelectTask even though the task has been deleted. It won't have any ill-effects, just be aware.
Let's walk through what's happening in a bit more detail:
First, the tasks variable is created from useState. This same variable is used throughout the component, which is totally fine and normal.
// created here
const [ tasks, setTasks ] = useState( dummyTasks );
const [ activeTask, setActiveTask ] = useState();
const deleteTask = ( taskToDeleteKey ) =>{
setActiveTask( null );
// referenced here, no big deal
setTasks( tasks.filter( task => task.key !== taskToDeleteKey ));
};
const handleSelectTask = ( taskToSelect, key ) =>{
setActiveTask( taskToSelect );
// tasks is referenced here, too, awesome
const newTaskArray = tasks.map( task => {
if( task.key === key ){
task.isActive = true;
}else{
task.isActive = false;
}
return task;
});
setTasks( newTaskArray );
};
Where the trouble comes in, is that if both of the functions are trying to update the same state value in the same render cycle, they will both be referencing the original value of the tasks array, even if the other function has attempted to update the state value! In your case, because the handleSelectTask is running after deleteTask, this means that handleSelectTask will update state using the array that hasn't been modified! When it runs, it will still see two items in the array, since the tasks variable won't change until the update is actually committed and everything rerenders. This makes it look like the delete portion isn't functioning, when really its effect is just being discarded since handleSelectTask isn't aware that the delete happened before it.
Lucas, this is not an issue with Context or Provider.
The problem that you are facing is actually a mechanism known as event bubbling where the current handler executes followed by parent handlers.
More info on event bubbling could be found here. https://javascript.info/bubbling-and-capturing.
In your case first, the handleDelete function gets called followed by handleSelect function.
Solution: event.stopPropagation();
Change your handleDelete and handleSelect function to this
const selectTask = () => {
console.log("handle select called");
handleSelectTask(task, taskTabKey);
};
const handleDelete = event => {
console.log("handle delete called");
event.stopPropagation();
deleteTask(taskTabKey);
};
Now check your console and you will find only the handle delete called will print and this would solve your problem hopefully.
If it still doesn't work then do let me know. I will create a codesandbox version for you.
Happy Coding.

React state change does not result in a rerender

I'm using React Infinite Scroller to render a list of posts.
My load more results function is called 3 times and therefore the result is updated three times (can be seen with a console.log)
I render the posts with:
{results.map((result) => (
<Widget data={result} key={result.id} />
))}
This updates the result the first two times, but when the state changes for the third time, it doesn't render any more results.
My full code:
import React, { useState } from "react";
import InfiniteScroll from "react-infinite-scroller";
import LoadingIndicator from "./loading";
import { request } from "../communication";
const InfiniteResults = ({ endpoint, widget }) => {
let [results, setResults] = useState([]);
let [hasMoreResults, setHasMoreResults] = useState(true);
const Widget = widget;
function loadMoreResults(page) {
// prevent from making more requests while waiting for the other one to complete
setHasMoreResults(false);
request
.get(endpoint, {
offset: page * 10,
})
.then(function gotResults(response) {
const data = response.data;
const resultsCopy = results;
data.results.forEach(function saveResultToState(result) {
resultsCopy.push(result);
});
setResults(resultsCopy);
console.log(resultsCopy);
console.log(results);
if (!data.next) {
setHasMoreResults(false);
} else {
setHasMoreResults(true);
}
});
}
return (
<InfiniteScroll
pageStart={-1}
loadMore={loadMoreResults}
hasMore={hasMoreResults}
loader={<p key={0}>Loading...</p>}
>
{results.map((result) => {
console.log("rerender");
return <Widget data={result} key={result.id} />;
})}
</InfiniteScroll>
);
};
export default InfiniteResults;
Your problem is with your state update:
const resultsCopy = results;
data.results.forEach(function saveResultToState(result) {
resultsCopy.push(result);
);
setResults(resultsCopy);
When you do const resultsCopy = results;, you're not actually copying the array; you're just referring to the same array by another name. That means that when you start adding elements to it, you are adding them directly to the one controlled by React's useState hook. All state updates should be done through the setState (setResults in your case) function that useState returns.
To perform an update on the previous state, the best way to do that is to call the setResults function with a function as an argument, that takes the previous state as its own argument. This ensures that the state updates are sequential (each update happens after the previous one was completed).
setResults(prevState => prevState.concat(data.results));
// or
setResults(function (prevState) {
return prevState.concat(data.results);
});
Here I have also made use of the concat function that combines two arrays into one and returns the result. That way you are not updating the previous state with the push calls.

Why is my React component is rendering twice?

I don't know why my React component is rendering twice. So I am pulling a phone number from params and saving it to state so I can search through Firestore. Everything seems to be working fine except it renders twice... The first one renders the phone number and zero points. The second time it renders all the data is displayed correctly. Can someone guide me to the solution.
class Update extends Component {
constructor(props) {
super(props);
const { match } = this.props;
this.state = {
phoneNumber: match.params.phoneNumber,
points: 0,
error: ''
}
}
getPoints = () => {
firebase.auth().onAuthStateChanged((user) => {
if(user) {
const docRef = database.collection('users').doc(user.uid).collection('customers').doc(this.state.phoneNumber);
docRef.get().then((doc) => {
if (doc.exists) {
const points = doc.data().points;
this.setState(() => ({ points }));
console.log(points);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
const error = 'This phone number is not registered yet...'
this.setState(() => ({ error }));
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
} else {
history.push('/')
}
});
}
componentDidMount() {
if(this.state.phoneNumber) {
this.getPoints();
} else {
return null;
}
}
render() {
return (
<div>
<div>
<p>{this.state.phoneNumber} has {this.state.points} points...</p>
<p>Would you like to redeem or add points?</p>
</div>
<div>
<button>Redeem Points</button>
<button>Add Points</button>
</div>
</div>
);
}
}
export default Update;
You are running your app in strict mode. Go to index.js and comment strict mode tag. You will find a single render.
This happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.
From the docs:
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:...
^ In this case the render function.
Official documentation of what might cause re-rendering when using React.StrictMode:
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
This is because of React Strict Mode code.
Remove -> React.StrictMode, from ReactDOM.render code.
Will render 2 times on every re-render:
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Will render 1 time:
ReactDOM.render(
<>
<App />
</>,
document.getElementById('root')
);
React is rendering the component before getPoints finishing the asynchronous operation.
So the first render shows the initial state for points which is 0, then componentDidMount is called and triggers the async operation.
When the async operation is done and the state been updated, another render is triggered with the new data.
If you want, you can show a loader or an indicator that the data is being fetched and is not ready yet to display with conditional rendering.
Just add another Boolean key like isFetching, set it to true when you call the server and set it to false when the data is received.
Your render can look something like this:
render() {
const { isFetching } = this.state;
return (
<div>
{isFetching ? (
<div>Loading...</div>
) : (
<div>
<p>
{this.state.phoneNumber} has {this.state.points} points...
</p>
<p>Would you like to redeem or add points?</p>
<div>
<button>Redeem Points</button>
<button>Add Points</button>
</div>
</div>
)}
</div>
);
}
React.StrictMode, makes it render twice, so that we do not put side effects in following locations
constructor
componentWillMount (or UNSAFE_componentWillMount)
componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)
componentWillUpdate (or UNSAFE_componentWillUpdate)
getDerivedStateFromProps
shouldComponentUpdate
render
setState updater functions (the first argument)
All these methods are called more than once, so it is important to avoid having side-effects in them. If we ignore this principle it is likely to end up with inconsistent state issues and memory leaks.
React.StrictMode cannot spot side-effects at once, but it can help us find them by intentionally invoking twice some key functions.
These functions are:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method
Function component bodies
State updater functions (the first argument to setState)
Functions passed to useState, useMemo, or useReducer
This behaviour definitely has some performance impact, but we should not worry since it takes place only in development and not in production.
credit: https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/
it is done intentionally by react to avoid this
remove
<React.StrictMode> </React.StrictMode>
from index.js
I worked around this by providing a custom hook. Put the hook below into your code, then:
// instead of this:
useEffect( ()=> {
console.log('my effect is running');
return () => console.log('my effect is destroying');
}, []);
// do this:
useEffectOnce( ()=> {
console.log('my effect is running');
return () => console.log('my effect is destroying');
});
Here is the code for the hook:
export const useEffectOnce = ( effect => {
const destroyFunc = useRef();
const calledOnce = useRef(false);
const renderAfterCalled = useRef(false);
if (calledOnce.current) {
renderAfterCalled.current = true;
}
useEffect( () => {
if (calledOnce.current) {
return;
}
calledOnce.current = true;
destroyFunc.current = effect();
return ()=> {
if (!renderAfterCalled.current) {
return;
}
if (destroyFunc.current) {
destroyFunc.current();
}
};
}, []);
};
See this blog for the explanation.
Well, I have created a workaround hook for this. Check this, if it helps:
import { useEffect } from "react";
const useDevEffect = (cb, deps) => {
let ran = false;
useEffect(() => {
if (ran) return;
cb();
return () => (ran = true);
}, deps);
};
const isDev = !process.env.NODE_ENV || process.env.NODE_ENV === "development";
export const useOnceEffect = isDev ? useDevEffect : useEffect;
CodeSandbox Demo: https://github.com/akulsr0/react-18-useeffect-twice-fix
React internally monitors & manages its render cycles using its virtual dom and its diffing algorithms, so you need not worry about the number of re-renders. Let the re-renders to be managed by react. Even though the render function is getting invoked, there are sub components which doesn't gets refreshed on ui, if there is no props or state change inside it. Every setstate function call will inform react to check the diffing algorithm, and invoke the render function.
So in your case, since you have a setstate defined inside the getPoints function, it tells react to rerun the diffing process through the render function.

Categories