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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.