This is more of a theoretical question and we use states for such cases but let’s say: since every React component is a function, why nothing happens when we call it within itself like the example below. Shouldn’t calling the function cause the component to render itself again?
const CallComp = () => {
let title = "Not clicked yet.";
const clickHandler = () => {
title = "Clicked!";
CallComp();
};
return (
<>
<div>{title}</div>
<button onClick={clickHandler}>Test</button>
</>
);
};
export default CallComp;
2
Answers
A render function doesn’t usually have side effects; in particular, it doesn’t have the side effect of actually mounting the component on the page. Rather, the render function is called by React, and it returns information to React to tell it what to display. If the render function is called other than by React, well, that has no effect, unless its caller decides to do something with whatever the render function returns.
You can’t call a react function in itself because it is breaking the rules of react hooks
if you want to rerender a component then use useState();