1

What happens to a function when a component re-renders in react? Is it recreated everytime?

export default function App() {
  console.log("rendered");
  const [isOpen, setisOpen] = useState(false);
  function handleClick() {
    setisOpen(true);
  }
  return (
    <div className="App">
      <button onClick={handleClick}>Click</button>
      {isOpen && <div>Secret is opened.</div>}
    </div>
  );
}

Why does this component renders 3 times?

2

1 Answer 1

0

On every render of the parent function it's child function gets created in order to prevent this you can use react hook called useCallBack

    import React, { useCallback } from 'react'
    export default function App() {
       console.log("rendered");
       const [isOpen, setisOpen] = useState(false);
       const handleClick = useCallback(() => {
         setisOpen(true);
       }, []);

      return (
        <div className="App">
          <button onClick={handleClick}>Click</button>
          {isOpen && <div>Secret is opened.</div>}
        </div>
      );
    }

here [] means this child function will be created once when parent function rendered

Sign up to request clarification or add additional context in comments.

2 Comments

Hey Anku. Thanks for the response. I don't see the use of Callback here. Even if we do that, we are still getting 3 renders.
If you are calling this App component in some other component as child component then you need to use React.memo() hook to prevent re rendering re rendering will only occur when any props passed to this App component will change read this article you will get the idea dmitripavlutin.com/use-react-memo-wisely

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.