Categories
React

React for Beginner: The Variable Scope

When you need to start to React development as a new skill, there is something related to variable scope you should get attended.

The code before using React

export default el => {
  let mapState = null

  if (apiKey) {
    mapState = new Map(apiKey)
  }

  console.log(mapState) // now it will be an object
} 

The difference when you start with React is useState and useEffect

import { useState, useEffect } from 'react'

const MapComponent = props => {
  // We don't specify "mapState" in traditional way
  const [mapState, setMapState] = useState(null)

  console.log(mapState) // return null if we don't have useEffect() below

  useEffect(() => {
    if (apiKey) {
      const map = new Map(apiKey)

      setMapState(map)
    }
  }, [apiKey])


  return (
     <div id="map"></div>
  )
}

export default MapComponent

What do you learn from the above example?

  • First, you don’t need to specify let and set variable before. Instead of that, it’s good to work with useState()
  • useState() could declarated with two things: mapState is an object name, and set+objectName (in this case: setMapState) will be a function to set object a different value. The key set isn’t permantly, so you can defind other verb as well, like const [background, removeBackground] = useState(null). But keep the key match with your object will reduce your stress time as well.
  • useEffect() could be your way to run a function, based on what you wish to rely. In above example, we reply apiKey until it is not undefined to create const map. Notice if you reply in array, you should check arr.length

Leave a Reply

Your email address will not be published.