Class variables vs state with React Native

12 Feb 2018

Global variables are assigned on app load. For example:

import React, { Component } from 'react'
import {
} from 'react-native'
const exampleGlobal = 'Helloooo, global variable here'

exampleGlobal will be executed when we run react native run ios.

Class variables will be assigned on loading of a component (ie when we navigate to the screen with the component). As the class variable declaration occurs in the contructor method, we can not assign a value to the class variable in another method after the contructor. For example, this will work:

class ImaClass extends Component {
  constructor() { = 'woof'

  componentDidMount() {
    if ( == 'tweet')
      console.log('That's not a dog')

whereas this will not work as we like:

class ImaClass extends Component {
  constructor() { = null

  componentDidMount() { = 'meow'
    if ( == 'meow')
      console.log('Ye ol cat features')

If we want to set a component value after the constructor then we should use this.setState({cat}) for example.