React tips I wish I knew back then

React tips every beginner should know - my opinionated version

I came up with a small list of things I wish I knew when I started to learn React that save a lot of time and efforts now and want to share them with you. This article does not explain core concepts of React and won’t give you a crash course of writing views in it but rather some tips that would make the development experience more pleasant and easier.

React Fragments

It’s a common case in React when your components need to return several html elements that you want to reuse later in your code. Let’s look at the example from react docs. In our <Table/> we want to use <Columns/> which returning nothing more then couple <td>s.

class Table extends React.Component {
  render() {
    return (
      <table>
        <tr>
          <Columns />
        </tr>
      </table>
    );
  }
}

Note, that we can’t just return those as React will throw error - Adjacent JSX elements must be wrapped in an enclosing tag. So we have an option of providing a single parent container, which can be <div> in this case.

class Columns extends React.Component {
  render() {
    return (
      <div>
        <td>Hello</td>
        <td>World</td>
      </div>
    );
  }
}

Two components mentioned above are totally valid and work with our producing any errors, but you may frequently stumble on unpleasant fact that wrapping everything into a <div> will often break layout or would create a necessity for additional in most cases redundant CSS.

Solution - Fragments

React offers a really neat workaround with its native Fragment syntax. All the layout problems can be mitigated by using them

class Columns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <td>Hello</td>
        <td>World</td>
      </React.Fragment>
    );
  }
}

Moreover you can also use shorter syntax and declare fragment in the following way. It’s highly likely that it’s supported by up to date versions of tools you are using with react, but in case it’s not - <React.Fragment> is always an option!

	<>
		<td>Hello</td>
        <td>World</td>
	</>

Conditional rendering

Often you need to add conditional rendering logic in your components. Let’s think of a case of when you want to render login button if user hasn’t entered his credentials yet, and logout if user is already signed in.

Quick and nice way of doing that is using ternary operator that looks at evaluated condition isLoggedIn in our case and if it’s true - returns the block after ?, if false - after :.

isLoggedIn = true
isLoggedIn ? <LogoutComponent/> : <LoginComponent>

What if you want to render just one element according to some condition?

Let’s think of a case where we get a response from the server with messages and want to display <AllMessages/> component dependent on its length. If it has length we want our component to be displayed, if not we don’t want to use it at all.

We can again use ternary operator but provide null as a returned statement if there are no messages. In JSX it will mean that our <AllMessages/> won’t render at all.

messages.length ? <AllMessages/> : null

But in this case ternary operator is redundant and we can shorten our conditional rendering with short circuit operator which is a neat javascript hack.

messages.length && <AllMessages/> 

The above mentioned code works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

I must say that I have been for long time abusing ternary operator even for such simple case and short circuit operator looks a lot cleaner and easier to read, especially it would be valid in nested conditional rendering logic which sometimes is required by application.

Dev Tools

I have been missing the fact that react dev tools has a little gear icon on the side of it which allows you to set a theme for your dev tools and also turn on the highlighting of elements being rerendered.

dev tools

If theme is rather cosmetic and allows you to set your favorite look to dev tools, rerender highlights can be of great importance when you want to check if your component does unneeded rerenders in a visual way!

Destructuring props and state

When you are just starting you are probably using this.state and this.props on a frequent basis and I know how tedious it can be to type tens of this.props with different prop names in dozens of components.

To simplify your life you can use object destructing to allow a simpler approach to accessing your props and state in render method. In our render method of class component in React we can get our props once and use them just with name, age and date rather than this.props.name etc. with the following code:

const {name, age, date} = this.props

Same goes with state:

const {name, age, date} = this.state

In our functional components we can also destructure our props and it looks even cleaner and easier there:

Let’s refactor this code and suddenly we need to write less boilerplate.

const Component = ({developer}) => {
  return (
    <div>
      <ul className="dev-profile" >
        <li>{developer.name}</li>
        <li>{developer.age}</li> 
     </ul>
   </div>

Let’s move further! This is a neat trick that I learned not so long ago - in javascript you can do nested destructuring which means we can access name and age from the author and use them as easy as that.

const Component = ({developer : { name, age }}) => {
  return (
    <div>
      <ul className="dev-profile" >
        <li>{name}</li>
        <li>{age}</li> 
     </ul>
   </div>

Styled-components

Finally I reached the technology which I can’t recommend enough. When I switched from writing CSS and using CSS Modules and then using classnames library to manage styles based on props and then keeping that mess with the classNames to styled-components I felt a huge relief.

This library has everything that you need to style your components and offers nice APIs so that you don’t have classNames all over your JSX bur rather semantically friendly names for your elements with styles injected automatically. I didn’t intend to write much about how to use styled-components because it’s for sure matter of separate post but have a look at this:

	<StyledInfoWrapper>
      <StyledInfo>
        Visuals with minimalist approach
      </StyledInfo>
      <SocialBlock />
	</StyledInfoWrapper>

It’s just a way of writing the code below👇 but it’s much more pleasant to work with. And I haven’t even mentioned how easy it is to adapt your styles with props!

	<div className='info-wrapper'>
      <div className='info'>
        Visuals with minimalist approach
      </div>
      <div className='social-block'/>
	</div>

Thanks for reading 🙏

I really hope that I at least persuaded you to try out couple of those new things if you haven’t heard of them before and I would much appreciate if you reach out to me ontwitter with your questions regarding anything covered in this blogpost.


Comments section

Dimitri Ivashchuk

Written by Dimitri who lives and works in Vienna building useful things. He is passionate about modern web technologies and enjoys learning something new everyday as well as sharing his knowledge with others.

Front-end engineer @CubeTech
Instructor @egghead.io