A few thoughts on working with React

I have been working with React since 2019, here is a few things that observed while working, mentoring and doing a lot of React code reviews.

  • The state isn't necessary. The values can be derived from other state/props.

  • This useEffect isn't necessary. The values can be derived on each render instead.

  • This useMemo isn't necessary. Let's execute this piece of code on each render instead. Premature optimization is the root of all evil.

  • All these booleans can be a single string enum.

  • Prefer passing named function to useEffect.

// What's happening here?
useEffect(() => {
  // do stuff here
}, [])

// Nice, tracking user - purpose is documented.
useEffect(function trackUser() {
  // do stuff here
}, [])

  • I prefer (event) over (e) simply because of:
    • Consistency
    • Readability
function Form(){
  return (
    // avoid
    <input onChange={(e) => {...}} />

    // prefer
    <input onChange={(event) => {...}} />
  )
}
  • Prefer Early Returns in your components

function ShowPost() {
  const post = useSomeStore(postId)

  if(!post) {
    return (
      <PostNotFound />
    )
  }

  return (  
    <PostDetails post={post} />
  )
}

Last updated on: 2024-04-01