skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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();

    import "./styles.css";
    import {useState} from "react" // import useState
    
    export default function App() {
      return (
        <CallComp/>
      );
    }
    const CallComp = () => {
      // let title = "Not clicked yet."; this does not cause a re-render
      const [title, setTitle] = useState("Not clicked yet."); // so you need to use useState if you want to re-render
      const clickHandler = () => {
        setTitle("Clicked!")
        // CallComp(); this line breaks the rules of react hooks
      };
      return (
        <>
          <div>{title}</div>
          <button onClick={clickHandler}>Test</button>
        </>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search