Props & State Cheat Sheet

Here’s a simple cheat sheet with some basic things you might want to do with props and state.

Setting Props

<SomeComponent color="red" show={false} />

Using Props

function SomeComponent(props) {
  console.log(props.show)

  return (
    <p>
      { props.color }
    </p>
  )
}

Destructuring Props

function SomeComponent({ color, show }) {
  console.log(show)

  return (
    <p>
      { color }
    </p>
  )
}

Creating State

const [size, setSize] = useState("large")
const [user, setUser] = useState({
  name: "Matilda"
})

Using State

console.log(size)

return (
  <p>
    { user.name }
  </p>
)

Passing State Down Through Props

function ParentComponent() {
  const [greeting, setGreeting] = useState("hi!")

  return (
    <p>
      <ChildComponent message={greeting} />
    </p>
  )
}

function ChildComponent({ message }) {
  return (
    <p>
     { message }
    </p>
  )
}

Setting State

const [size, setSize] = useState("large")
const onButtonClick = () {
  setSize("small")
}

const [show, setShow] = useState(false)
const showModal = () => {
  setShow(true)
}

Rules of Setting State

  1. Handle asynchronous setting of state
  2. Don’t mutate state directly

With some state updates, neither rule applies.

With objects and arrays, both rules apply.

1. Handle Asynchronous Setting of State

If you’re updating state based on the previous state, you need to use a function.

Some examples of updating based on previous state:

  • Adding to/subtracting from a number
  • Changing one property/some properties on an object, and leaving the rest unchanged
  • Adding/removing/updating part of an array, and leaving the rest of the array unchanged

Code Examples:

// Add 15.99 to the total
setTotal( currTotal => currTotal + 15.99 )

// Make the user an admin
setUser( currUser => { ...currUser, isAdmin: true } )

// Delete a todo from the list
setTodoList( currList => currList.filter(
  todo => todo.id !== idToDelete 
)

2. Don’t Mutate State Directly

If you’re working with objects or arrays, don’t mutate them directly, work off of a copy.

Making a copy of an object:

const copyOfUser = { ...user }

Making a copy of an array:

const copyOfTodoList = [ ...todoList ]

const copyOfUserList = userList.slice()

(Using array methods is another way to work off copies)

Code Examples:

// Change the user’s name
setUser( currUser => { ...currUser, name: "Jose" } )

// Add a new todo to the list
setTodoList( currList => [ ...currList, newTodo ] )

// Update the name of a user in the list
setUserList( currList => currList.map(
  user => (user.id === idToUpdate)
    ? { ...user, name: "Simone" } 
    : user
)

Leave a Reply

Your email address will not be published. Required fields are marked *