side effect in useMemoOne
See original GitHub issuehttps://codesandbox.io/s/condescending-poitras-zp2t7?file=/src/App.js
import React, { useState, useMemo } from "react";
import { useMemoOne } from "use-memo-one";
import "./styles.css";
export default function App() {
const [state, setState] = useState(0);
const [count, setCount] = useState(0);
useMemoOne(() => {
setState(count + 10);
}, [count]);
return (
<div className="App">
<h1>{count}</h1>
<h2>{state}</h2>
<button onClick={() => setCount((c) => c + 1)}>setCount</button>
</div>
);
}
If it has some side effect in useMemoOne, like set other state, it makes App re-render. And this useMemoOne will run again though count if not changed, which causes the infinite loop.
Use React.useMemo
will be OK.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:14 (3 by maintainers)
Top Results From Across the Web
Is okay to useMemo instead of useEffect for calling side-effect ...
No. You should use useEffect hook for side-effects. useMemo returns a memoized value. const memoizedValue = useMemo(() ...
Read more >Issues · alexreardon/use-memo-one - GitHub
Contribute to alexreardon/use-memo-one development by creating an account on GitHub. ... side effect in useMemoOne. #21 opened on Sep 16, 2020 by auver....
Read more >use-memo-one - Bountysource
import React, { useState, useMemo } from "react"; import { useMemoOne } from "use-memo-one"; import "./styles.css"; export default function App() { const ...
Read more >Understanding common frustrations with React Hooks
Unfortunately, the lack of side effects makes these stateless components a bit limited, and in the end, something somewhere must manipulate ...
Read more >Hooks Considered Harmful - Hacker News
2. https://github.com/alexreardon/use-memo-one ... The entire "no side effect" aspect of functional programming is just a huge misunderstanding at best.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@miuirussia No it doesn’t say that. If you refer to this:
the bold text above is talking about
getDerivedStateFromProps
not about calling setState (inside a condition) during render.Although indeed OPs callback passed to
useMemoOne
wouldn’t fit in the description of allowed callback based on the quote from react docs which you mention (because it uses setState without condition), but still it is interesting if we replaceuseMemoOne
withuseMemo
in OPs example, it doesn’t suffer same issue.Yes, but it is clearly written there that you should not do this