Should I wrap every prop with useCallback or useMemo, when to use this hooks?How to pass props to this.props.childrenReact props not correctly set when wrapping an inputHow to store props passed on Click of an event in ReactTrigger onChange when new props are receivedReact child component state not updating when new props are passedReact.js onclick event: Cannot read property 'props' of undefinedReact hooks useMemo/useCallback skipPerformance penalty of creating handlers on every render with react-hooksReact useState - setValue rerenders the component even though the value is the sameReact Hooks useCallback causes child to re-render
Picking a theme as a discovery writer
Can an Iranian citizen enter the USA on a Dutch passport?
Hostile Divisor Numbers
What's the 2-minute timer on mobile Deutsche Bahn tickets?
What is a common way to tell if an academic is "above average," or outstanding in their field? Is their h-index (Hirsh index) one of them?
What is the meaning of 「隣のおじいさんは言いました」
Endgame puzzle: How to avoid stalemate and win?
Copper as an adjective to refer to something made of copper
Make me a minimum magic sum
Collision domain question
What is monoid homomorphism exactly?
Given four points how can I find an equation for any pattern?
Dual frame in Riemannian metrics.
Ab major 9th chord in Bach
A 2-connected graph contains a path passing through all the odd degree vertices
Given a safe domain, are subdirectories safe as well?
HSA - Continue to Invest?
Debian 9 server no sshd in auth.log
Emergency stop in plain TeX, pdfTeX, XeTeX and LuaTeX?
Can anyone identify this unknown 1988 PC card from The Palantir Corporation?
TIP120 Transistor + Solenoid Failing Randomly
Reverse ColorFunction or ColorData
Summer '19 Sandbox error: String index out of range: 0: Source
How important are good looking people in a novel/story?
Should I wrap every prop with useCallback or useMemo, when to use this hooks?
How to pass props to this.props.childrenReact props not correctly set when wrapping an inputHow to store props passed on Click of an event in ReactTrigger onChange when new props are receivedReact child component state not updating when new props are passedReact.js onclick event: Cannot read property 'props' of undefinedReact hooks useMemo/useCallback skipPerformance penalty of creating handlers on every render with react-hooksReact useState - setValue rerenders the component even though the value is the sameReact Hooks useCallback causes child to re-render
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
With react hooks now available should I in case of functional components wrap every function passed with props with useCallback and every other props value with useMemo?
Also having custom function inside my component dependent on any props value should I wrap it with useCallback?
What are good practices to decide which props or const values from component wrap with this hooks ?
If this improves performance why not to do it at all times ?
Lets consider custom button where we wrap click handler and add custom logic
function ExampleCustomButton( onClick )
const handleClick = useCallback(
(event) =>
if (typeof onClick === 'function')
onClick(event);
// do custom stuff
,
[onClick]
);
return <Button onClick=handleClick />;
Lets consider custom button where we wrap click handler and add custom logic on condition
function ExampleCustomButton( someBool )
const handleClick = useCallback(
(event) =>
if (someBool)
// do custom stuff
,
[someBool]
);
return <Button onClick=handleClick />;
Should i in this two cases wrap my handler with useCallback ?
Similar case with use memo.
function ExampleCustomButton( someBool )
const memoizedSomeBool = useMemo(() => someBool, [someBool])
const handleClick = useCallback(
(event) =>
if (memoizedSomeBool)
// do custom stuff
,
[memoizedSomeBool]
);
return <Button onClick=handleClick />;
In this example I even pass memoized value to useCallback.
Another case what if in the component tree many components memoize same value ? How does this impact performance ?
reactjs react-hooks
add a comment |
With react hooks now available should I in case of functional components wrap every function passed with props with useCallback and every other props value with useMemo?
Also having custom function inside my component dependent on any props value should I wrap it with useCallback?
What are good practices to decide which props or const values from component wrap with this hooks ?
If this improves performance why not to do it at all times ?
Lets consider custom button where we wrap click handler and add custom logic
function ExampleCustomButton( onClick )
const handleClick = useCallback(
(event) =>
if (typeof onClick === 'function')
onClick(event);
// do custom stuff
,
[onClick]
);
return <Button onClick=handleClick />;
Lets consider custom button where we wrap click handler and add custom logic on condition
function ExampleCustomButton( someBool )
const handleClick = useCallback(
(event) =>
if (someBool)
// do custom stuff
,
[someBool]
);
return <Button onClick=handleClick />;
Should i in this two cases wrap my handler with useCallback ?
Similar case with use memo.
function ExampleCustomButton( someBool )
const memoizedSomeBool = useMemo(() => someBool, [someBool])
const handleClick = useCallback(
(event) =>
if (memoizedSomeBool)
// do custom stuff
,
[memoizedSomeBool]
);
return <Button onClick=handleClick />;
In this example I even pass memoized value to useCallback.
Another case what if in the component tree many components memoize same value ? How does this impact performance ?
reactjs react-hooks
Well, definitely not every time, all the time : ) Their use is situational. I'd say look into actually using these when you start experiencing performance hurdles.
– Powell Ye
Mar 25 at 12:58
Thanks @Powell_v2 for your comment, but if this improves performance why not to do it at all times ?
– Vardius
Mar 26 at 5:29
I guess if that was viable, React would to it automatically instead of exposing these as separate APIs. As @jalooc pointed out, there are costs associated with memoizing callbacks/values. Code cluttering is also a concern.
– Powell Ye
Mar 27 at 13:00
If the click handler doesn't use any of the component'sprops
within it, then you can declare it outside of the component and then the handler function won't get re-created on every prop change of the component (since it's outside..)
– vsync
Apr 1 at 8:20
add a comment |
With react hooks now available should I in case of functional components wrap every function passed with props with useCallback and every other props value with useMemo?
Also having custom function inside my component dependent on any props value should I wrap it with useCallback?
What are good practices to decide which props or const values from component wrap with this hooks ?
If this improves performance why not to do it at all times ?
Lets consider custom button where we wrap click handler and add custom logic
function ExampleCustomButton( onClick )
const handleClick = useCallback(
(event) =>
if (typeof onClick === 'function')
onClick(event);
// do custom stuff
,
[onClick]
);
return <Button onClick=handleClick />;
Lets consider custom button where we wrap click handler and add custom logic on condition
function ExampleCustomButton( someBool )
const handleClick = useCallback(
(event) =>
if (someBool)
// do custom stuff
,
[someBool]
);
return <Button onClick=handleClick />;
Should i in this two cases wrap my handler with useCallback ?
Similar case with use memo.
function ExampleCustomButton( someBool )
const memoizedSomeBool = useMemo(() => someBool, [someBool])
const handleClick = useCallback(
(event) =>
if (memoizedSomeBool)
// do custom stuff
,
[memoizedSomeBool]
);
return <Button onClick=handleClick />;
In this example I even pass memoized value to useCallback.
Another case what if in the component tree many components memoize same value ? How does this impact performance ?
reactjs react-hooks
With react hooks now available should I in case of functional components wrap every function passed with props with useCallback and every other props value with useMemo?
Also having custom function inside my component dependent on any props value should I wrap it with useCallback?
What are good practices to decide which props or const values from component wrap with this hooks ?
If this improves performance why not to do it at all times ?
Lets consider custom button where we wrap click handler and add custom logic
function ExampleCustomButton( onClick )
const handleClick = useCallback(
(event) =>
if (typeof onClick === 'function')
onClick(event);
// do custom stuff
,
[onClick]
);
return <Button onClick=handleClick />;
Lets consider custom button where we wrap click handler and add custom logic on condition
function ExampleCustomButton( someBool )
const handleClick = useCallback(
(event) =>
if (someBool)
// do custom stuff
,
[someBool]
);
return <Button onClick=handleClick />;
Should i in this two cases wrap my handler with useCallback ?
Similar case with use memo.
function ExampleCustomButton( someBool )
const memoizedSomeBool = useMemo(() => someBool, [someBool])
const handleClick = useCallback(
(event) =>
if (memoizedSomeBool)
// do custom stuff
,
[memoizedSomeBool]
);
return <Button onClick=handleClick />;
In this example I even pass memoized value to useCallback.
Another case what if in the component tree many components memoize same value ? How does this impact performance ?
reactjs react-hooks
reactjs react-hooks
edited Mar 26 at 5:28
Vardius
asked Mar 23 at 4:45
VardiusVardius
3,02133568
3,02133568
Well, definitely not every time, all the time : ) Their use is situational. I'd say look into actually using these when you start experiencing performance hurdles.
– Powell Ye
Mar 25 at 12:58
Thanks @Powell_v2 for your comment, but if this improves performance why not to do it at all times ?
– Vardius
Mar 26 at 5:29
I guess if that was viable, React would to it automatically instead of exposing these as separate APIs. As @jalooc pointed out, there are costs associated with memoizing callbacks/values. Code cluttering is also a concern.
– Powell Ye
Mar 27 at 13:00
If the click handler doesn't use any of the component'sprops
within it, then you can declare it outside of the component and then the handler function won't get re-created on every prop change of the component (since it's outside..)
– vsync
Apr 1 at 8:20
add a comment |
Well, definitely not every time, all the time : ) Their use is situational. I'd say look into actually using these when you start experiencing performance hurdles.
– Powell Ye
Mar 25 at 12:58
Thanks @Powell_v2 for your comment, but if this improves performance why not to do it at all times ?
– Vardius
Mar 26 at 5:29
I guess if that was viable, React would to it automatically instead of exposing these as separate APIs. As @jalooc pointed out, there are costs associated with memoizing callbacks/values. Code cluttering is also a concern.
– Powell Ye
Mar 27 at 13:00
If the click handler doesn't use any of the component'sprops
within it, then you can declare it outside of the component and then the handler function won't get re-created on every prop change of the component (since it's outside..)
– vsync
Apr 1 at 8:20
Well, definitely not every time, all the time : ) Their use is situational. I'd say look into actually using these when you start experiencing performance hurdles.
– Powell Ye
Mar 25 at 12:58
Well, definitely not every time, all the time : ) Their use is situational. I'd say look into actually using these when you start experiencing performance hurdles.
– Powell Ye
Mar 25 at 12:58
Thanks @Powell_v2 for your comment, but if this improves performance why not to do it at all times ?
– Vardius
Mar 26 at 5:29
Thanks @Powell_v2 for your comment, but if this improves performance why not to do it at all times ?
– Vardius
Mar 26 at 5:29
I guess if that was viable, React would to it automatically instead of exposing these as separate APIs. As @jalooc pointed out, there are costs associated with memoizing callbacks/values. Code cluttering is also a concern.
– Powell Ye
Mar 27 at 13:00
I guess if that was viable, React would to it automatically instead of exposing these as separate APIs. As @jalooc pointed out, there are costs associated with memoizing callbacks/values. Code cluttering is also a concern.
– Powell Ye
Mar 27 at 13:00
If the click handler doesn't use any of the component's
props
within it, then you can declare it outside of the component and then the handler function won't get re-created on every prop change of the component (since it's outside..)– vsync
Apr 1 at 8:20
If the click handler doesn't use any of the component's
props
within it, then you can declare it outside of the component and then the handler function won't get re-created on every prop change of the component (since it's outside..)– vsync
Apr 1 at 8:20
add a comment |
2 Answers
2
active
oldest
votes
Not worth it, for multiple reasons:
- Even official docs say you should do it only when necessary.
- Keep in mind that premature optimization is the root of all evil :)
- It makes DX (developer experience) far worse: it's harder to read; harder to write; harder to refactor.
- When dealing with primitives (like in your example) memoizing costs more CPU power than not doing it. A primitive value doesn't have a concept of references, so there's nothing to memoize in them. On the other hand, memoization itself (as any other hook) does require some tiny processing, nothing is for free. Even though it's tiny, it's still more than nothing (compared to just passing a primitive through), so you'd shoot your own foot with this approach.
To put all together - you'd waste more time typing all the hooks than a user would gain on having them in the application if you want to put them everywhere. The good old rule applies: Measure, then optimize.
add a comment |
I agree with the principles proposed by @jalooc
To give some more insight about the exhibited use cases in the OP, here is my advice:
Expensive children renders
function Component()
const callback = useCallback(() => dostuff , [deps])
return <Child prop=callback />
The above makes sense if Child
is a very expensive component to render. As such, it is probably exported like so:
function Child()
...this takes significant CPU...
// Export as a pure component
export default React.memo(Child)
Expensive computations
function Component( foo )
// This very expensive computation will only run when it's input (foo)
// changes, allowing Component to re-render without performance issues
const bar = useMemo(() =>
... something very complicated with `foo` ...
, [foo])
return <div>bar</div>
Conclusion
- Do what makes sense or that have measured bad performance
- If a function that changes at render causes derived expensive computations, memoize it (
useCallback
) or move it outside the scope if you can. - If a component itself is expensive to render, make it pure with
React.memo
, with the help of#2
if necessary - If something IS itself expensive to re-compute, memoize it (
useMemo
) - Do what makes sense or that have measured bad performance
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310682%2fshould-i-wrap-every-prop-with-usecallback-or-usememo-when-to-use-this-hooks%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Not worth it, for multiple reasons:
- Even official docs say you should do it only when necessary.
- Keep in mind that premature optimization is the root of all evil :)
- It makes DX (developer experience) far worse: it's harder to read; harder to write; harder to refactor.
- When dealing with primitives (like in your example) memoizing costs more CPU power than not doing it. A primitive value doesn't have a concept of references, so there's nothing to memoize in them. On the other hand, memoization itself (as any other hook) does require some tiny processing, nothing is for free. Even though it's tiny, it's still more than nothing (compared to just passing a primitive through), so you'd shoot your own foot with this approach.
To put all together - you'd waste more time typing all the hooks than a user would gain on having them in the application if you want to put them everywhere. The good old rule applies: Measure, then optimize.
add a comment |
Not worth it, for multiple reasons:
- Even official docs say you should do it only when necessary.
- Keep in mind that premature optimization is the root of all evil :)
- It makes DX (developer experience) far worse: it's harder to read; harder to write; harder to refactor.
- When dealing with primitives (like in your example) memoizing costs more CPU power than not doing it. A primitive value doesn't have a concept of references, so there's nothing to memoize in them. On the other hand, memoization itself (as any other hook) does require some tiny processing, nothing is for free. Even though it's tiny, it's still more than nothing (compared to just passing a primitive through), so you'd shoot your own foot with this approach.
To put all together - you'd waste more time typing all the hooks than a user would gain on having them in the application if you want to put them everywhere. The good old rule applies: Measure, then optimize.
add a comment |
Not worth it, for multiple reasons:
- Even official docs say you should do it only when necessary.
- Keep in mind that premature optimization is the root of all evil :)
- It makes DX (developer experience) far worse: it's harder to read; harder to write; harder to refactor.
- When dealing with primitives (like in your example) memoizing costs more CPU power than not doing it. A primitive value doesn't have a concept of references, so there's nothing to memoize in them. On the other hand, memoization itself (as any other hook) does require some tiny processing, nothing is for free. Even though it's tiny, it's still more than nothing (compared to just passing a primitive through), so you'd shoot your own foot with this approach.
To put all together - you'd waste more time typing all the hooks than a user would gain on having them in the application if you want to put them everywhere. The good old rule applies: Measure, then optimize.
Not worth it, for multiple reasons:
- Even official docs say you should do it only when necessary.
- Keep in mind that premature optimization is the root of all evil :)
- It makes DX (developer experience) far worse: it's harder to read; harder to write; harder to refactor.
- When dealing with primitives (like in your example) memoizing costs more CPU power than not doing it. A primitive value doesn't have a concept of references, so there's nothing to memoize in them. On the other hand, memoization itself (as any other hook) does require some tiny processing, nothing is for free. Even though it's tiny, it's still more than nothing (compared to just passing a primitive through), so you'd shoot your own foot with this approach.
To put all together - you'd waste more time typing all the hooks than a user would gain on having them in the application if you want to put them everywhere. The good old rule applies: Measure, then optimize.
answered Mar 27 at 7:25
jaloocjalooc
501517
501517
add a comment |
add a comment |
I agree with the principles proposed by @jalooc
To give some more insight about the exhibited use cases in the OP, here is my advice:
Expensive children renders
function Component()
const callback = useCallback(() => dostuff , [deps])
return <Child prop=callback />
The above makes sense if Child
is a very expensive component to render. As such, it is probably exported like so:
function Child()
...this takes significant CPU...
// Export as a pure component
export default React.memo(Child)
Expensive computations
function Component( foo )
// This very expensive computation will only run when it's input (foo)
// changes, allowing Component to re-render without performance issues
const bar = useMemo(() =>
... something very complicated with `foo` ...
, [foo])
return <div>bar</div>
Conclusion
- Do what makes sense or that have measured bad performance
- If a function that changes at render causes derived expensive computations, memoize it (
useCallback
) or move it outside the scope if you can. - If a component itself is expensive to render, make it pure with
React.memo
, with the help of#2
if necessary - If something IS itself expensive to re-compute, memoize it (
useMemo
) - Do what makes sense or that have measured bad performance
add a comment |
I agree with the principles proposed by @jalooc
To give some more insight about the exhibited use cases in the OP, here is my advice:
Expensive children renders
function Component()
const callback = useCallback(() => dostuff , [deps])
return <Child prop=callback />
The above makes sense if Child
is a very expensive component to render. As such, it is probably exported like so:
function Child()
...this takes significant CPU...
// Export as a pure component
export default React.memo(Child)
Expensive computations
function Component( foo )
// This very expensive computation will only run when it's input (foo)
// changes, allowing Component to re-render without performance issues
const bar = useMemo(() =>
... something very complicated with `foo` ...
, [foo])
return <div>bar</div>
Conclusion
- Do what makes sense or that have measured bad performance
- If a function that changes at render causes derived expensive computations, memoize it (
useCallback
) or move it outside the scope if you can. - If a component itself is expensive to render, make it pure with
React.memo
, with the help of#2
if necessary - If something IS itself expensive to re-compute, memoize it (
useMemo
) - Do what makes sense or that have measured bad performance
add a comment |
I agree with the principles proposed by @jalooc
To give some more insight about the exhibited use cases in the OP, here is my advice:
Expensive children renders
function Component()
const callback = useCallback(() => dostuff , [deps])
return <Child prop=callback />
The above makes sense if Child
is a very expensive component to render. As such, it is probably exported like so:
function Child()
...this takes significant CPU...
// Export as a pure component
export default React.memo(Child)
Expensive computations
function Component( foo )
// This very expensive computation will only run when it's input (foo)
// changes, allowing Component to re-render without performance issues
const bar = useMemo(() =>
... something very complicated with `foo` ...
, [foo])
return <div>bar</div>
Conclusion
- Do what makes sense or that have measured bad performance
- If a function that changes at render causes derived expensive computations, memoize it (
useCallback
) or move it outside the scope if you can. - If a component itself is expensive to render, make it pure with
React.memo
, with the help of#2
if necessary - If something IS itself expensive to re-compute, memoize it (
useMemo
) - Do what makes sense or that have measured bad performance
I agree with the principles proposed by @jalooc
To give some more insight about the exhibited use cases in the OP, here is my advice:
Expensive children renders
function Component()
const callback = useCallback(() => dostuff , [deps])
return <Child prop=callback />
The above makes sense if Child
is a very expensive component to render. As such, it is probably exported like so:
function Child()
...this takes significant CPU...
// Export as a pure component
export default React.memo(Child)
Expensive computations
function Component( foo )
// This very expensive computation will only run when it's input (foo)
// changes, allowing Component to re-render without performance issues
const bar = useMemo(() =>
... something very complicated with `foo` ...
, [foo])
return <div>bar</div>
Conclusion
- Do what makes sense or that have measured bad performance
- If a function that changes at render causes derived expensive computations, memoize it (
useCallback
) or move it outside the scope if you can. - If a component itself is expensive to render, make it pure with
React.memo
, with the help of#2
if necessary - If something IS itself expensive to re-compute, memoize it (
useMemo
) - Do what makes sense or that have measured bad performance
edited Mar 29 at 11:05
answered Mar 29 at 0:09
PandaioloPandaiolo
3,88622153
3,88622153
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310682%2fshould-i-wrap-every-prop-with-usecallback-or-usememo-when-to-use-this-hooks%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Well, definitely not every time, all the time : ) Their use is situational. I'd say look into actually using these when you start experiencing performance hurdles.
– Powell Ye
Mar 25 at 12:58
Thanks @Powell_v2 for your comment, but if this improves performance why not to do it at all times ?
– Vardius
Mar 26 at 5:29
I guess if that was viable, React would to it automatically instead of exposing these as separate APIs. As @jalooc pointed out, there are costs associated with memoizing callbacks/values. Code cluttering is also a concern.
– Powell Ye
Mar 27 at 13:00
If the click handler doesn't use any of the component's
props
within it, then you can declare it outside of the component and then the handler function won't get re-created on every prop change of the component (since it's outside..)– vsync
Apr 1 at 8:20