Joseph Jude

Consult . Code . Coach

Simple tutorial to understand props vs state in React.js


code . nodejs . tsc . react

I have been learning React.js (and blogging about it).

Components, are an essential building blocks in react.js. As I learned about them, I couldn't understand the difference between props and state of a react.js component.

This guide explains my understanding of props and state.

Props

props is short for properties. Like parameters in functions, you can pass properties into react.js component.

Consider this simple example:

// define a component with a props

interface Props { name: string }

class Hello extends React.Component<Props, any> {
  render() {
    return <h1>Hello from {this.props.name}!</h1>;
  }
}

// invoke the component by passing props
ReactDOM.render(
  <Hello name="Joseph"> />,
    document.getElementById("main")
);

Here the class Hello is a component that accepts a property. Later in the code, we invoke the component by passing the name property.

Because this is Typescript, we can define the structure of this property, as an interface.

Components can read the property but can't modify it.

State

A state object is owned by the component. It is used when a component has to create and update an information.

State is created by component in the constructor and changed with setState method.

Let us see both property and state in action in the following example.

In this example, we are going to display a timer on the browser. We will start with a certain value and at the tick of every second, the app will decrement that value and display it in the browser.

We will use props to send the initial value, and state to track the changes in that value and also to display that current value.

We will create a Timer component first.

If you want to understand the basics of React.js component, read Create React.js component with Typescript.

import * as React from "react";

interface Props { startWith: number }
interface State { currentValue: number }

export class Timer extends React.Component<Props, State> {

  constructor(props: Props) {
    super(props);

    this.state = { currentValue: this.props.startWith }

    setInterval(() => {
      this.setState({ currentValue: this.state.currentValue - 1 })
    }, 1000);
  }

  render() {
    return (
      <div className="Timer">
        {this.state.currentValue}
      </div>
    )
  }
}

The Timer component takes startsWith as a property and holds currentValue as a state. The startsWith property will be an input from the invoking component with the inital value for the Timer. As the timer tickes, the currentValue stores the changes in the timer and renders the modified value.

A state is created in the constructor and initialized. Its value is changed using setState.

A React.js component has to render itself. This timer component renders its currentValue. Whenever a setState is invoked, React.js automatically calls its render function.

Let us see how to invoke this Timer component with an initial value.

import * as React from "react";
import * as ReactDOM from "react-dom";

import { Timer } from "./components/Timer";

ReactDOM.render(
  <Timer startWith={500} />,
  document.getElementById("main")
);

Now that we understand props and state, I'm going to change the Timer component little bit. The setState is asynchronous. The above code may not work in some cases because React.js may batch update. We are going to take this async nature into account and change the Timer component.

setInterval(() => {
  this.setState((prevState: State, props: Props) => ({
    currentValue: prevState.currentValue - 1
  }))
}, 1000);
}

setState is a function with two parameters—prevState, and props. We get the previous currentValue from prevState and decrement it.

Let us recap. props is used to send information to the component. A component can not modify props. A component can create and modify state to track information. To modify state, use setState. Because of the async nature, use prevState to access its previous value. Whenver a component calls setState, React.js calls its corresponding render function.

This is part of Learning React.js with Typescript series.

If you liked this article, subscribe with the below form to get new articles in this series.


Like the post? Retweet it. Got comments? Reply.

Simple tutorial to understand props vs state in React.js by @jjude: https://t.co/SZvZuL2bqI

— Joseph Jude (@jjude) June 28, 2017
Share this on: Twitter / /

Comments

comments powered by Disqus