Last active
May 10, 2022 15:12
-
-
Save maacpiash/fd91a5c4958617efe2c1813bcf5fb4d6 to your computer and use it in GitHub Desktop.
React mistakes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react' | |
export default function App() { | |
const [title, setTitle] = useState({ | |
firstTitle: 'Java', | |
secondTitle: 'Script', | |
renderCount: { | |
value: 0, // this will increase by 1 every time the button is clicked | |
comment: 'The count value preserves the count of the clicks.' // a constant. no change ever. | |
}, | |
meta: { | |
renderDate: new Date().toLocaleDateString(), // this will remain a constant between clicks (and renders). | |
renderTime: new Date().toLocaleTimeString() // this will also remain the same. | |
} | |
}) | |
useEffect(() => console.log(JSON.stringify(title, null, 2)), [title]) | |
const handleClick = () => setTitle(prevState => ({ | |
...prevState, | |
firstTitle: 'React', | |
secondTitle: 'JS', | |
renderCount: { | |
...prevState.renderCount, | |
value: prevState.renderCount.value + 1 | |
} | |
// no need for `meta: { ...prevState.meta }` because it's not being updated. | |
})) | |
const handleClickNoIncrement = () => setTitle(prevState => ({ | |
...prevState, | |
firstTitle: 'React', | |
secondTitle: 'JS', | |
})) | |
return ( | |
<div style={{ display: 'flex', gap: '3px', flexDirection: 'column', alignItems: 'flex-start' }}> | |
<h2>{title.firstTitle + ' ' + title.secondTitle}</h2> | |
<button onClick={handleClick}>Set title to React JS</button> | |
<button onClick={handleClickNoIncrement}>Set title to React JS (no increment)</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment