So, after a long discussion with peers, and an even longer online research -- Stack Overflow and what not -- you have finally chosen to go with React. You have successfully neglected frameworks and libraries such as Angular, Vue and even Jquery after a long consideration for your upcoming project. Congratulations, you have successfully been influenced.

Well, that was my story at least, to an extent. I started digging through different libraries and frameworks after I realized Angular.js 1.6 wasn't that much of a help. That was 2 years ago. I had built a personal blog after getting frustrated with Medium (where is my money, huh?) and decided to go with Angular.js -- easy to start, eh? The site was done and pushed to production only to start finding out the bad in it (We can talk of the bad later), and thus the digging began.

Over the next few weeks, I dug deep -- every blog and medium article -- and that is where I came to my initial conclusion -- it will either be Angular 2 or React. Going forward I found something unique about the way react was designed, for instance -- HTML inside JS? Cool. Finally, my initial frustration with Angular.js directives and other framework components paid off, and I decided to give React a try, after all, it was just a blog. Not to mention, Angular 2 isn't bad, it's just I chose to go with React at that time plus, you know, online influence (Dan Abramov still continues to influence, positively, be sure to follow him).

Now, coming back to the article, I told this story because I wanted to let you know it's not long that I started writing React apps and I believe that I am qualified enough to write an article targeted to beginners. This article contains the tips that I wish I got from someone when I started writing this blog with React (yes, it still has a lot of issues!). I have written every single point based on my own experience over the last 2 years. I hope you find these helpful. Let's begin!

1. Keep components in their dedicated folders

I may not have chosen to go with Angular (ng 2, for short) but I did borrow its structuring idea. With ng 2, when you create a component using CLI like this,

ng generate component "component-name"

you would notice that it creates a folder for the component, with .ts, .css, .spec.ts, and .html files inside it. We follow the same pattern. A component must reside inside a dedicated folder carrying the same name as the component, and the sub-components will continue the same pattern inside the parent folder. Benefits? It makes for a clean organization of code components.

One more thing that I borrowed is the idea of keeping CSS files for each component or in react, for each .js file. That way we can focus on styling a component without breaking down any other component style. One more benefit it gives is that we can completely ignore a component and it won't add to the overall class size, i.e; we won't mistakenly include the unused CSS. Neat, right? Oh and also, the .css file goes in the same folder as the js component. Better make a habit!

2. Difference between Props and State

When just starting with React, people often get confused with props and state. The simplest of the answers to this is, State is mutable and is based within the component itself -- the parent or other components can't touch or update it.

Props, on the other hand, are immutable -- can't be changed within the component itself, more like a final (or constant) value. They only get updated whenever the parent component does so.  Props are a way for the parent component to pass data to the child component or more realistically named, dumb component. Let's see how props and state are different with a simple example. This is our parent that renders the Child with two props namely, name and age, that contain the user's name and age respectively.

class Parent extends React.Component {
  render() {
  return( <Child name={ 'Nilesh' }  age={ 23 } /> )
  }
}

The child component, on the other hand, looks something like this,

class Child extends React.Component {
  render() {
    return (
  <div>
      <span>Username: { this.props.name } </span>
      <span>Age: { this.props.age } </span>
    </div>
)
  }
}

Notice the use of props in the child component? Props are nothing more than special attributes for the child components that the parent sets during render. The child can make use of those to then set data values during its render. Once the props are passed down the hierarchy, they can't be mutated by the Child receiving it.

States, as I said earlier, are designed to be of mutable nature so that the component itself could handle changes without the need of the parent updating props. The state is there for the component to handle its internal changes, for example, on a click of a button within the Child component, the username should change from `Nilesh Singh` to `John Doe` -- this we can't do with props since they are immutable at child level. So we define a state within Child like this,

class Child extends React.Component {
  constructor(props) {
   super(props)
   this.state = { username: 'Nilesh Singh' }
}
}

Yes, the state is simply a JavaScript object that holds all the values as keys and values. Also, the state should always be defined within the constructor so that React could build it up during construction to avoid null or undefined values during render.

Once we are done with initializing the state, we can use it everywhere within the component. Let's set this username state as our username in render and manually change it on a button's click.

handleClick(e) {
  this.setState(prevState => {
  return { username: 'John Doe' }
})
}
render() {
    return (
      <div>
        <span>Username: { this.state.username } </span>
        <span>Age: { this.props.age } </span>
        <button onClick={ this.handleClick.bind(this) }>Change Username</button>
      </div>
    )
}

Notice that on the click of the button, the handleClick function is called, which then uses a special method, setState(...) to update the current state. So, why am I calling it a special method? We could simply update the username property of the state object without the method, by doing this,

this.state.username = 'John Doe'

Sure, we can but this is not going to change anything on the UI side, i.e no text won't change to 'John Doe' at all in <span/>. It will simply change the value, no re-render at all. In order to re-render, we ought to call the setState(...) method which will then update the username to 'John Doe' and then after will call the render(...) method of our component as to reflect the value change in the UI. 

However, you would notice that the username value is changing only the first time, then after it remains the same, so what does react do here -- after all, we are calling the setState(...) method on every click, no matter if the value changes or not. Well, this is the part where React really shines. Sure, the render method is triggered every time setState is called but React first checks for a real value change by building up the virtual DOM, matches it with native DOM and then updates the native DOM if there is a difference detected. You could read more about virtual DOM and how it works here.

One more thing, Props and State both can be used to set values to one another but that doesn't mean they can be used in one another's place. Keep them separate and try to minimize state updates, as each state update triggers a re-render, and even if the Native DOM doesn't change due to unchanged value(s), it is worth noting that Virtual DOM itself eats up some cycles to be built up and matched (diffed). One simple example of state and props being used to set up one another is,

render() {
  return  (<Child name={ this.state.name } />)
}

or 

class Child extends React.Component {
  constructor(props) {
  this.state = {
  username: this.props.name
}
}
}

Oh and yes, please always remember that not only a change in state causes a re-render of the component, but also the change in props triggers the same.

3. Avoid useless containers, use Fragments instead

There are times when we need to have a hierarchy of components in our React application. While it is quite easy to do so in React, one thing that we often ignore is the structure of the HTML call i.e; we often keep useless container HTML tags that don't even serve a purpose in the hierarchy. For example,

g assume we have a parent class which calls a child component named Child. The structure of the parent is like this,

<div className="parent">
  <Child></Child>
</div>

Now, our child component does just one thing, says that is is a child. The div around that text will prove to be useless, as it doesn't control the text within it, had it have a class bound to it or even style, it would have proved to be useful to some degree but here it doesn't. 

<div>
  Hi, This is a child!
</div>

So, after the parent HTML renders with child HTML inside it, the final HTML would look something like this,

<div className="parent">
  <div> <!-- Useless div -->
    Hi, This is a child!
  </div>
</div>

See, the second div is useless -- no control what so ever over the next child i.e; text. We could have ignored that but again we need to wrap each component within a tag, right? Sure, we do, but we can replace this <div> or any other HTML tag, with an internal React component that makes sure when the parent calls the child, the inner children of that special react component will be rendered without the component itself. This special component is called Fragment.

Now, our child component with this Fragment will look like this,

<>
  Hi, This is a child!
<>

or if you have an error with the syntax above, you may use this syntax for fragment instead. Remember to import Fragment in the module first, though.

import { Fragment } from 'react';

<Fragment>
  Hi, This is a child!
</Fragment>

And now when this new updated child of ours is called by the parent, it would look something like this when it renders completely,

<div className="parent">
  Hi, This is a child! 
</div>

See, the useless div has been eliminated successfully. What React does while changing the virtual DOM to real DOM is that it just returns the children of the Fragment component like this, 

render() {
  return this.props.children
}

This may look like a bit of a hard work, identifying useless container tags and replacing them with Fragments, but it will pay off in the long term when the interface has a huge hierarchy size and renders start suffering.

4. Always unsubscribe to events and handlers in components

React makes it easier to handle events in components by giving an equivalent synthetic event, for example, onclick becomes onClick in React which demands a callback function,

<button onClick={ this.handleClick.bind(this) }>Click Me</button>

That seems simple and easy to use, isn't it? Well, it is quite simple if you have a synthetic event available as React will take care of that, but what if we don't get one?

For example, Window resize change event is not available within React, so we need to rely on the document event listener for that. We could use the listener like this after our component has mounted,

componentDidMount() {
   window.addEventListener('resize', this.sizeChanged);
}
sizeChanged() {
  // size changed
console.log(window.innerWidth, window.innerHeight)
}

and be able to read the screen size whenever the browser window size changes. But always choose to remove the event listener after its purpose is over in the context or the component is simply done (or destroyed) to avoid a memory leak. We can remove the event listener by calling the removeEventListener in componentWillUnmount -- which indicates the component is about to be removed or destroyed.

componentWillUnmount() {
    window.removeEventListener('resize', this.sizeChanged)
}

The same goes for the timeout or intervals. Once they are deemed no longer useful, always make sure you remove them be it in componentWillUnmount or in any other lifecycle method. This is a common mistake that programmers make while building apps ignoring the chances of a memory leak in the app.

5. Avoid Useless classes

Another mistake beginners generally make is assuming that every component has to be a class. Not necessarily. If your component does nothing more than returning a bunch of HTML based upon the props passed (or not), use a function instead. Such a setup is also called functional stateless component, as such a component can't have a state as it is simply a plain javascript function return HTML.

One more thing to keep in mind is that alongside state, you also don't get lifecycle methods with functional component, so if a component is dependent on lifecycle hooks or has to have local state, choose to go with a class-based component.

A simple example of a functional stateless component is,

function Child( props ) {
  return (
  <div>Hello from a stateless component: { props.name }</div>
  )
}

6. Make use of proxy

Chances are you will get in a situation where you would have to query a local API that you might be developing on the same machine. No problem, you can query with http://localhost:8080 in case you're running your dev server on port 8080. A sample request would look something like this,

fetch('http://localhost:8080/api/my-endpoint')
  .then(res => res.json())
  .then(data => {
    console.log('Received:', data);
})

This kind of a set up makes sense until you start building your app for production or need to query a different endpoint URL altogether. This is where proxy comes in. React gives us a proxy feature with which we can define an alternate endpoint to which the requests from within react need to go. Neat, isn't it?

One can set up a proxy with React by adding a proxy attribute in the package.json file and set the alternate URL as its value something like,

{
  "name": "my-react-app",
  "version": "0.0.1",
  "private": true,
  "proxy": "http://localhost:6000", //this is where magic happens
  "dependencies": {
   ...
}
}

This is really helpful in maintaining a clean and organized structure of requests, that only go to the proxy endpoint. Think of it as an interceptor (like Ng 2 interceptor) where React redirects your requests with base paths to the proxy endpoint instead of itself. After setting up the proxy as above, we can do this

fetch('/api/my-endpoint')
  .then(res => res.json())
  .then(data => {
     console.log('Received:', data);
   })

and our requests will start going to http://localhost:6000. Oh and yes, make sure you restart react (with npm start) after you have added the proxy to package.json.

7. Better use Create-React-App

Most tutorials online (generally the old ones) suggest that you start off your React learning from the very basics, by setting up all the configs such as webpack, babel and what not. That seems okay for one project, I agree --  you get the idea of the things under the hood that make the magic happen, but once you move from just a project to multi-projects, it becomes a pain to copy the same configs and files over and over again to different directories. Also, you are increasing the chances of a reusing an obsolete piece of code with such an organization.

To avoid such a problem, it is now recommended to use the Create-React-App CLI (command line interface) to create a new React app. With Create-React-App tool we get the complete initial structure for our React project, webpack and babel set up, and other dependency installations handled. Just run the following npm command (with global flag) and you are can use the tool globally.

npm install -g create-react-app

Once done, run these commands to (1) create your app with name, my-react-app, then (2) move the project directory just created by the tool, and then finally (3) start the React app with npm start.

create-react-app my-react-app
cd my-react-app/
npm start

No need to configure anything, the tool handles everything. However, that also presents an issue -- you can't really make changes to webpack or presets (babel) with such a setup unless you go back to the normal setup, with the project being treated as a boilerplate and webpack and other dependencies bloat the package.json file.

Create-react-app does give you the ability to move out. You can go back to the normal set up with,

npm run eject

However, I would suggest otherwise -- stick with create-react-app tool only. Don't bring the overhead of managing multiple config files, or updating react every time or even to keep the package.json clean and loaded with useful metadata, let other things be handled by the system (the tool).

# What next?

6 of these 7 practices are optional, but it is highly recommended to keep these in mind and in your regular use to build a more efficient React app. These may seem like a lot in the beginning but believe me, once you get used to, you will find them to be saving a lot of time and resources for you.

With that, we are done for this article. I know these are just 7 practices of many more that every beginner should have a knowledge of, but it will be unfair to make a single article unnecessarily long and throw a lot to consume to a beginner. We will be publishing more such articles targetting React dev beginners in the coming weeks. Be sure to subscribe to our newsletter to be in the loop and get the latest articles we post here.