Overview

React.js is simple library used for building complex UI interfaces with small blocks called components. React enables creating Single Page Applications (SPA) in easy way. SPA is web application that loads once and every next request on page should reload only affected components without refreshing entire page. React is able to do it by operating on virtual DOM (Document Object Model). In simple words java script creates tree of components and based on user’s requests changes nodes and rebuilds tree. Having it working in this way, each component renders content independently, without reloading entire page.

 

Stateless & Stateful Components

React has two different types of components: Stateful and Stateless. As name suggest first one can have own state, second not (it’s possible from version 16.8.0 after introducing mechanism called Hooks)

Stateful

class Component extends React.Component {
    render(){
        return(<div>Hello from Stateful Component</div>)
    }
}

Stateless

Stateless component is just a function that returns HTML node.

const Component = () => {
    return(<div>Hello from Stateless Component</div>)
}

or even simpler

const Component = () => (<div>Hello from Stateless Component</div>)

 

State

Components in React can hold own state, generally we should try to create more stateless components than stateful but sometimes this is necessary. State is just JSON object accessible from component.

Declaring state

We can initialize state in constructor in this way

class Person extends React.Component {
  constructor(props){
    this.state = { name: null }
  }
  render() {
    return(<div></div>
  }
}

We can also declare it directly in component without creating constructor.

class Person extends React.Component {
  state = {
    name: null
  }

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

Using state

If You want to get data from state only thing is using this.state. Getting data from state sounds simply but updating state in similar way is common mistake. You can’t change state of component by assigning values to this.state. To update state correctly we should use setState() method that gets new state as an argument. This method causes not only update but also rendering component. I described this method below in section about React methods.

Hooks

From version 16.8.0 React allow using state in stateless component. This is possible by using something called hooks. Hooks allow us to create simple and clear code without writing stateful components.

Example usage:

const MyComponent  = () => {
  const [name, setName] = useState(null);
  return(
    <div>
      <div>My components name {name}</div>
      <button onClick={()=>setName("Changed Name")}>Change Name</button>
    </div>)
}

As You can see only thing to do is declaring variable and setter method. Argument that we are passing to useState is initial value.

 

Props

Props are values that we can pass to component from it’s parent. In simple words we can think about it like about arguments that we can pass to function. Passing new props to component triggers its render method. This means that every time when You will pass new data there React will rebuild this part of DOM.

Example:

const Component = ( {name} ) => {     
  return(
    <div>Hello {name}</div>
  ) 
}


<div>
  <Component name='Michal'>
</div>

Usage in way like below will result by creating following HTML

<div>
  <div>Hello Michal</div>
<div>

PropTypes

Although JavaScript is dynamic type language (which means that we don’t define types explicitly) React supports something called PropTypes. We can define which values or types we expect to receive from parent component. There are many options that we can define here. We can tell React that we expect object, string, any specific value, shape (object that have specific fields) or array. PropTypes declaration looks as folows but first we have to import PropTypes from prop-types package.

ComponentName.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number,
  settings: PropTypes.shape({
    color: PropTypes.oneOf(['red','blue']),
    subscriptionIds: PropTypes.array
  }).isRequired,
  isActive: PropTypes.bool
}

DefaultProps

For every properties that parent can pass to children we can set some default values in case when no values were sent. For that purpose we use defaultProps statement.

ComponentName.defaultProps = {
  settings: {
    color: 'red',
    subscriptionIds: [1,2]
  }
}

 

Context

Context is mechanism that allows passing data through entire component tree without having to pass props down manually at every level. It’s rather advanced feature and we can use it for example for creating themes in our application. Styled-Components library is one of the popular library that is using it to ease creating reusable css variables. You can read more about context on official page.

 

Lifecycle methods

Lifecycle methods are functions that react runs automatically during entire life of component. They are helping us to prepare data in appropriate moment, register listeners, improve performance and many more operations that require synchronization based on component’s state.

render()

This is sole method is React component lifecycle that we have to implement. This means that we always have to implement it. Render method is responsible for providing component’s HTML code to mechanisms that builds DOM tree. In simple words in this place we are writing HTML code mixed with CSS and JavaScript responsible for showing what we need on page.

constructor()

Purpose of constructor, like in any object oriented language, is creating component. We are implementing when we want to initialize local state (by assigning to this.state) or bind event handler methods. React runs constructor before mounting component.

componentDidMount()

componentDidMount() starts right after component mount. We can use this method in any initialization that requires DOM nodes. It can be good place for calling data from remote endpoint or triggering any animations.

componentDidUpdate()

React invokes componentDidUpdate() right after any update of component. Here we can also implement any API calls but worth to mention is that we should compare current and previous props to avoid unnecessary calls.

componentWillUnmount()

componentWillUnmount() runs immediately before unmounting and destroying components . Here we can perform any cleanup, unsubscriptions, invalidations or request cancellations.

shouldComponentUpdate()

Purpose of this method is checking if component changed state and should be rerendered. Implementation this method in right way can increase performance. Sometime it’s needed to just return false from there to avoid rerender of component (PureComponent is working exactly in this way).

static getDerivedStateFromProps()

static getDerivedStateFromProps() runs always right before render(). It should return object to update state or null when we want to inform React that no update is needed. This is really rarely used method.

getShapshotBeforeUpdate()

getShapshotBeforeUpdate() enables your component to get some information from DOM before it is potentially changes. Method will run right before our component’s updated structure is applied to DOM. Under the hood React passes result of this method as an argument to componentDidUpdate()

static getDerivedStateFromError()

React calls it after error occurrence in any child component. It gets and error and should return value to update state accordingly.

componentDidCatch()

React invokes componentDidCatch() after occurrence of any errors that descendant components throw. This method takes two parameters: error and componentStack. This is good place for things like error logging.

UNSAFE_componentWillMount()

Method that React runs just before mounting component. This is sole lifecycle method called on server-side rendering.

UNSAFE_componentWillReceiveProps()

Method runs before mounted component receives new props.

UNSAFE_componentWillUpdate()

UNSAFE_componentWillUpdate() runs just before rendering when state or pros have changed. We can use it for preparation before update occur.

 

Another methods in React component

setState()

Method that causes enqueuing  update state of component. We should see this operation more like a request rather than immediate command because React under the hood can optimize performance by delaying invocation. Method setState() almost always causes rerender, sole case when situation looks another is when shouldComponentUpdate() returns false.

forceUpdate()

Method causes rerender without taking care of current state and value that shouldComponentUpdate() returns.

 

Create-React-App

Create React App is tool for creating new React project with complete configuration in some predefined form. Using this tool allow us to start with example project that we can modify on our own and adapt to our needs.
To generate new project we only need to call appropriate command with name of project.

npx create-react-app my-new-example-application
cd my-new-example-application
npm start

Application that we generated opens automatically in browser under http://localhost:3000

Create React App is available here.

 

Create-next-app

Working and purpose of create-next-app is similar as decribed above. Sole differece is that this script will create a little bit another structure and will use another libraries. Goal of creating application using this script is supporting server-side rendering, this means that React application runs on server and browser will receive prepared HTML and CSS. This way of working allows search engines to find information on our page more effectively. SSR can also increase performance of application if someone runs it on slow machine. You can find more about this tool here.

 

Summary

React.js because of it’s simplicity and low entry barrier is my favorite library. I see trend that many companies prefer another frameworks like Angular because of it’s enterprise nature. From my perspective React nowadays is good substitution for that. From version 16 license is clear and “safe”, library is mature and is much more smaller in comparison to Angular. In case we want create lighter application we can use any smaller version of this library like Preact or Inferno. Authors of this libraries just got rid of seldom used parts. In case of Preact we don’t have events mechanism.

From my perspective React is perfect for people that are starting with frontend programming. It’s also good choice for small websites but in big one it is also able to show it’s power.

React unfortunately have bad things. For example Angular 2+, thanks to Angular CLI, have established project structure. In React there is no standard which means that team decides about project structure that mostly differs from project to project.

 

About author

Hi,
my name is Michał. I’m software engineer. I like sharing my knowledge and ideas to help other people who struggle with technologies and design of todays IT systems or just want to learn something new.
If you want to be up to date leave your email below or leave invitation on LinkedIn, XING or Twitter.

Add your email to be up to date with content that I publish


Leave a Reply

Your email address will not be published. Required fields are marked *