Skip to main content

Command Palette

Search for a command to run...

Best Practices in ReactJS with Typescript

Published
2 min read
Best Practices in ReactJS with Typescript

(Not Yet Completed)

  • A component should have a single responsibility

  • Use useMemo when required

  • Don’t Use Indexes as a Key Prop

  • give default props

  • use typescript class objects in components

  • use components only for View, for any business logic use typescript classes

  • do not hard code any strings, and try not to use string comparisons

  • Destructuring Props

bad

return (
  <>
    <div> {user.name} </div>
    <div> {user.age} </div>
    <div> {user.profession} </div>
  </>  
)

Good

const { name, age, profession } = user;

return (
  <>
    <div> {name} </div>
    <div> {age} </div>
    <div> {profession} </div>
  </>  
)
  • use ES6 Spread Function

  • Conditional rendering using &&

class FilterResult extends Component {
  render () {
  let { filterResults } = this.props;
  return (
    <section className="search-results">
      { filterResults.length > 0 &&
        filterResults.map(index => <Result key={index} {... results[index] />)
      }
      { filterResults.length === 0 &&
        <div className="no-results">No results</div>
      }
    </section>
  );
  }
}
  • Use try-catch to handle errors beyond boundaries

  • Avoid curly braces for string props

  • Use a fragment when a div is not needed

Bad

return (
  <div>
     <Component1 />
     <Component2 />
     <Component3 />
  </div>  
)

Good

return (
  <>
     <Component1 />
     <Component2 />
     <Component3 />
  </>  
)
  • Use Ternary Operators Bad
const { role } = user;

if(role === ADMIN) {
  return <AdminUser />
}else{
  return <NormalUser />
}

Good


const { role } = user;

return role === ADMIN ? <AdminUser /> : <NormalUser />
  • Remove JS Code From JSX Bad
return (
  <ul>
    {posts.map((post) => (
      <li onClick={event => {
        console.log(event.target, 'clicked!'); // <- THIS IS BAD
        }} key={post.id}>{post.title}
      </li>
    ))}
  </ul>
);

Good

const onClickHandler = (event) => {
   console.log(event.target, 'clicked!'); 
}

return (
  <ul>
    {posts.map((post) => (
      <li onClick={onClickHandler} key={post.id}> {post.title} </li>
    ))}
  </ul>
);
  • Use Template Literals Bad
const userDetails = user.name + "'s profession is" + user.proffession

return (
  <div> {userDetails} </div>  
)

Good

const userDetails = `${user.name}'s profession is ${user.proffession}`

return (
  <div> {userDetails} </div>  
)
  • Use Implicit return

    Bad

const add = (a, b) => {
  return a + b;
}

Good

const add = (a, b) => a + b;