I struggled to understand re-rendering and memoization in React for a long time. Today I wrote the article I wish I had read many years ago. The information is concise and to the point. I hope it helps someone.

image

Another trick is that the setter function from useState can accept a function. This can also help save unnecessary rerenders.

const [open, setOpen] = useState(false)
const toggleState = useCallback(() => setOpen(!open), [open])
const toggleStateCool = useCallback(() => setOpen(open => !open), [])

Why? if another hook depends on toggleState callback, it won’t require another rerender. Probably not useful if used in simple cases like toggling a state, but may be useful if you are making your own custom hooks with more complexity.

Author: Shantun Parmar

Leave a Reply

Your email address will not be published.