Please follow my code snippet below, When I click on any button (add, edit, remove) all my components gets re-render including the Title
component which has no props
or stats
. It may be fine if I have a few components but lets assume that I have over 15 or more with fetching / saving data, is that OK or should be avoided?
I've tried to use useCallback
hooks (with handleRemove) but obviously that doesn't work as intended.
const Button = ({ title, count, onClick }) => {
console.log(`Rendering ${title}`)
return (
<button onClick={onClick}>
{title} ({count})
</button>
)
}
const Header = () => {
console.log("Rendering Title")
return <h1>App Title</h1>
}
const Parent = () => {
const [add, setAdd] = React.useState(0)
const [edit, setEdit] = React.useState(0)
const [remove, setRemove] = React.useState(0)
const handleAdd = () => setAdd(add + 1)
const handleEdit = () => setEdit(edit + 1)
const handleRemove = React.useCallback(() => {
setRemove(remove + 1)
}, [remove])
return (
<React.Fragment>
<Header />
<Button title="Add" onClick={handleAdd} count={add} />
<Button title="Edit" onClick={handleEdit} count={edit} />
<Button title="Remove" onClick={handleRemove} count={remove} />
</React.Fragment>
)
}
function App() {
return (
<div className="App">
<Parent />
<button onClick={console.clear}>Clear log</button>
</div>
)
}
ReactDOM.render( <App /> , document.getElementById('root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>