Props vs State in React

I’ve recently started learning React. The Facebook React docs are fantastic for getting started, highly recommend.

Before I went completely through the docs I was getting very confused between Props and State in React, but as I went through the Docs I learnt some things to help distinguish them:

Props

  • Passed down from parent to child
  • Both class and function components can use props
  • Props are read only, they cannot be updated

State

  • State is set up when you create a component – i.e. in a constructor.
  • Only components that are built from classes can use state, components built from functions cannot.
  • Unlike props, state can be updated
  • Reserved for interactivity – i.e. state is updated by user in put

Is it a state or a prop?  (from React Docs)

  1. Is it passed in from a parent via props? If so, it probably isn’t state.
  2. Does it remain unchanged over time? If so, it probably isn’t state.
  3. Can you compute it based on any other state or props in your component? If so, it isn’t state.

Passing information up and down the inheritance tree

You pass information down via props.

You pass information up via callback (event handlers). Read these docs on how to lift state up, i.e., pass state up from child to parent, by using callbacks

A note on initialisers:

From the React Docs

The constructor is the right place to initialize state. If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

Side note about what I’m building in React:

The project I’ve decided to work on is an evolution of my High Tea app. This was one of the first Rails apps I ever built, back in 2013. I haven’t worked much on it since then, but have kept it going and done a few tweaks just because, unlike other little apps I made, this is one that I actually still use. I keep updating it with all the new High Teas I go to.

So, I’ve decided to create a React front end to it, and develop some API endpoints for my old app, so that I can practice some React.

Leave a reply