Update from obsidian - thinkpad
Affected files: .obsidian/workspace.json games/castlevania-symphony-of-the-night.md notes/utils/React.md projects/games.md
This commit is contained in:
parent
28a41d36ce
commit
3a87d09933
4 changed files with 119 additions and 29 deletions
|
|
@ -1,3 +1,58 @@
|
|||
## Typescript
|
||||
|
||||
- [Cheatsheet](https://react-typescript-cheatsheet.netlify.app)
|
||||
- [Cheatsheet](https://react-typescript-cheatsheet.netlify.app)
|
||||
|
||||
## Prevent UseEffect Infinite Loops
|
||||
|
||||
React use [shallow comparision](https://learntechsystems.com/what-is-shallow-comparison-in-js/) (values are equals in case of primitive types. In case of object it just check the reference) to check if the dependency changes between renders, this can conduce to bugs in the following situa
|
||||
|
||||
### Always use a depency array
|
||||
|
||||
```js
|
||||
useEffect(() => {
|
||||
setCount((count) => count + 1);
|
||||
}, []);
|
||||
```
|
||||
|
||||
### Function as dependency
|
||||
|
||||
React re defines functions on every render, so the dependency always changes, use `useCallback` to memoize the function so it doesn't change
|
||||
|
||||
```js
|
||||
const logResult = useCallback(() => {
|
||||
return 2 + 2;
|
||||
}, []);
|
||||
|
||||
useEffect(()=> {
|
||||
setCount((count) => count + 1);
|
||||
}, [logResult]);
|
||||
```
|
||||
|
||||
### Array as dependency
|
||||
|
||||
The reference to an array changes in every render, use `useRef` so it doesn't change
|
||||
|
||||
```js
|
||||
const [count, setCount] = useState(0);
|
||||
//extract the 'current' property and assign it a value
|
||||
const { current: myArray } = useRef(["one", "two", "three"]);
|
||||
|
||||
useEffect(() => {
|
||||
setCount((count) => count + 1);
|
||||
}, [myArray]);
|
||||
```
|
||||
### Object as dependency
|
||||
|
||||
The reference to an object changes in every render, use `useMemo` so it doesn't change
|
||||
|
||||
```js
|
||||
const person = useMemo(
|
||||
() => ({ name: "Rue", age: 17 }),
|
||||
[] //no dependencies so the value doesn't change
|
||||
);
|
||||
useEffect(() => {
|
||||
setCount((count) => count + 1);
|
||||
}, [person]);
|
||||
```
|
||||
|
||||
[source](https://blog.logrocket.com/solve-react-useeffect-hook-infinite-loop-patterns/)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue