Bytes are small code snippets that I think are worth sharing.
This works best if styles are not involved, depending on what type of styling you use.
This opinion will likely be very divisive, but I believe if you can get past your syntax pride, it might just 🤯 your 🧠and increase your productivity.https://t.co/N51J8iwKJb pic.twitter.com/Kk4BVxoamx
— Tanner Linsley (@tannerlinsley) March 4, 2022
Here’s an example of a component where the event handler has been written inline in the return statement:
const FooActivation = () => {
const [foo, setFoo] = useState(false)
return (
<button
onClick={() => {
setFoo(true)
console.log('Activated', foo)
}}
>
Activate
</button>
)
}
This practice can eat at browser memory if we aren’t careful. Instead of inlining our function to handle clicking the button, we extract it outside the return statement so that React doesn’t have to rerun that function on each render.
const FooActivation = () => {
const [foo, setFoo] = useState(false)
// only run once
const handleClick = (override?: boolean) => setFoo(override || true)
return (
<>
<button onClick={handleClick}>Activate</button>
{/* or if you have to pass in some data */}
<button onClick={() => handleClick(false)}>Activate</button>
</>
)
}
.filter(Boolean)
Also end up using this a lot
🔥 I do this all the time. It's pretty handy! Use .filter(Boolean) on an array and you can make your code much easier to follow via JavaScript expressions (like ternaries). pic.twitter.com/ccvWcTkbus
— Kent C. Dodds 💿 #RemixConf (@kentcdodds) June 21, 2018
:has()
for FormsOr another one: alter the label based on the validity of the input (given that the label targets the nearby input)
— Bramus (@bramus) December 21, 2021
🔗 https://t.co/8qwngmepVd pic.twitter.com/b0TMBCQ81F