const useSomeHook = ({number}) => {
const [newNumber, setNewNumber] = useState(0)
useEffect(() => {
setNewNumber(number + 1)
}, [number])
}
const SomeComponent = ({number, value, ...restProps}) => {
useSomeHook({number})
return <div>{number}</div>
}
Let's imagine I have this case. Each time when in SomeComponent
come some new prop, it will call my useSomeHook
hook, but I want to prevent it. I want to call it only when the number
is changed (memoize
it). In other cases, don't touch it. But I haven't found any solving with this case. Could you help me solve this issue?
Since components are just functions though, they can be memoized using React. memo() . This prevents the component from re-rendering unless the dependencies (props) have changed. If you have a particularly heavy component then it is best to memoize it, but don't memoize every component.
React has a built-in hook called useMemo that allows you to memoize expensive functions so that you can avoid calling them on every render. You simple pass in a function and an array of inputs and useMemo will only recompute the memoized value when one of the inputs has changed.
You can not prevent calling hook, this will lead to invariant violation error. Every hook in component should be executed on each render. You should rely on useEffect
dependencies argument to run conditional code only if value changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With