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 withuseState()
useState()
could declarated with two things:mapState
is an object name, andset+objectName
(in this case:setMapState
) will be a function to set object a different value. The keyset
isn’t permantly, so you can defind other verb as well, likeconst [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 replyapiKey
until it is not undefined to createconst map
. Notice if you reply in array, you should checkarr.length