React useState in 30 seconds

Jim Kang
Jim Kang
May 6, 2019 · 1 min read
Photo by Jay on Unsplash

First, Array destructure (< 5 seconds)

const [pikachu, eevee] = [25, 133];// pikachu = 25 (pokemon number)
// eevee = 133

Second, UseState (20 seconds)

const initialPokemon = 'charmander';
const state = useState(initialPokemon);
// state is an array
const pokemon = state[0];
// pokemon = 'charmander'
// use like a variable, NOT this.pokemon
const setPokemon = state[1];
// use like a function, ex. setPokemon('charmaleon')

Third, Combine (5 seconds)

const initialPokemon = 'charmander';
const [pokemon, setPokemon] = useState(initialPokemon);

Bonus (not counting time)

If an initial state is a function, it’ll only execute at initial render, this will boost performance if you’re loading expensive load at the beginning

const [pokemons, setPokemons] = useState(() => loadAllPokemon());
  1. setPokemons is like setState BUT WILL NOT SHALLOW MERGE!!!
// after you do this
setPokemons({ name:'charmander', number: 4});
// all other pokemon info are gone!!!!
console.log(pokemons)
// { name:'charmander', number: 4}
// think of mergePokemon = original setState
const mergePokemon = pokemon =>
setPokemon(otherPokemon => ({
...otherPokemon,
...pokemon
}));

Fullstack Memory Dump

notes, thoughts and troubles from a full stack learner

Jim Kang

Written by

Jim Kang

Fullstack Memory Dump

notes, thoughts and troubles from a full stack learner

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade