Notes

React State with Hooks

Edit on GitHub

ReactJS
2 minutes
 1import React, { useState } from 'react'
 2
 3export default function Demo () {
 4	const state = useState("")
 5	const text = state[0]
 6	const updateText = state[1]
 7
 8	// useState() is a function that takes the the initial state and returns an array
 9	// containing two items
10	// first item is the value you want to put in state
11	// second item is the function to update that value
12
13	// the above can be written in a shorthand way liek below
14	const [text, updateText] = useState("")
15
16	// every value you want to set in state gets its own line like above
17}
  • Hooks let you add state to a function component, no more constructor(), this, or this.setState()
  • useState() is a hook that returns an array. First entry is whatever value you want to put in the state. The second entry is a function to update the state. You can name these entries whatever you want.
  • Accessing state is as simple as referencing the variable {name}, since it’ll be in scope.
1const [checked, setChecked] = useState(false)
2
3const handleCheckboxToggle = e => setChecked(!checked)
4
5// You can also provide a function to the updator
6// pass previous state, return new state
7
8const handleCheckboxToggle = e => setChecked(prevChecked => !prevChecked)

The state can be an object too

 1const [state, setState] = useState({
 2	text: '',
 3	checked: false,
 4	loadning: false,
 5	data: []
 6})
 7
 8const handleCheckboxToggle = e => setState(prevState => ({
 9	checked: !prevState.checked // since the state is an object, you can have to specify which property, in this case `checked`
10}))

useState() does not do a shallow merge like setState() does, it wipes out the state that we had before. React recommends saving your state as separate variables so that updating one does not wipe the other. (Or you could write your own mergeState function)

1const mergeState = partialState => 
2setState(prevState => ({
3	...prevState, // takes new state being sent and merges with previous state
4	...partialState
5}))
6
7<input onChange={e => mergeState({ text: e.target.value })} />

Linting

If you want linting for your React Hooks, you’ll have to eject from the create-react-app project in order to install ES Lint