logo

React state update cheat sheet

State Updates

Arrays or objects should not be updated directly. Instead, there are special techniques to update arrays and objects by first creating a new array or object. Even though this requires some extra processing power, it allows React to do far less work when re-rendering a component.

State Updates


        const [colors, setColors] = useState(['red', 'green', 'blue']);

        const changeColor = () => {
          // Bad!  This directly changes the 'colors' state!
          colors[0] = 'orange';
        
          setColors(colors);
        };
      

Adding Elements to start of an Array

Elements can be added to the start of an array by using the spread syntax.

Adding Elements to start of an Array


        const [colors, setColors] = useState(['red', 'green']);

        const addColor = (colorToAdd) => {
          const updatedColors = [colorToAdd, ...colors];
          setColors(updatedColors);
        };
      

Adding Elements to end of an Array

Elements can be added to the end of an array by reversing the order of elements in updatedColors.

Adding Elements to end of an Array


        const [colors, setColors] = useState(['red', 'green']);

        const addColor = (colorToAdd) => {
          // Now 'colorToAdd' will be at the end
          const updatedColors = [...colors, colorToAdd];
          setColors(updatedColors);
        };
      

Adding Elements to index of an Array

Elements can be added at any index by using the slice method available on all arays.

Adding Elements to index of an Array


        const [colors, setColors] = useState(['red', 'green']);

        const addColorAtIndex = (colorToAdd, index) => {
          const updatedColors = [
            ...colors.slice(0, index),
            colorToAdd,
            ...colors.slice(index),
          ];
          setColors(updatedColors);
        };
      

Removing Elements by array index

Elements can be removed from an array by using the filter method.

Removing Elements by array index


        const [colors, setColors] = useState(['red', 'green', 'blue']);

        const removeColorAtIndex = (indexToRemove) => {
          const updatedColors = colors.filter((color, index) => {
            return index !== indexToRemove;
          });
        
          setColors(updatedColors);
        };
      

Removing Elements by array value

Elements can be removed from an array by using the filter method.

Removing Elements by array value


        const [colors, setColors] = useState(['red', 'green', 'blue']);

        const removeValue = (colorToRemove) => {
          const updatedColors = colors.filter((color) => {
            return color !== colorToRemove;
          });
        
          setColors(updatedColors);
        };
      

Modifying elements

Objects in an array can be modified by using the map function.

Modifying elements


        const [books, setBooks] = useState([
          { id: 1, title: 'Sense and Sensibility' },
          { id: 2, title: 'Oliver Twist' },
        ]);
        
        const changeTitleById = (id, newTitle) => {
          const updatedBooks = books.map((book) => {
            if (book.id === id) {
              return { ...book, title: newTitle };
            }
        
            return book;
          });
        
          setBooks(updatedBooks);
        };
      

Changing Properties In Objects

Properties in an object can be changed or added by using the spread syntax (the ...).

Changing Properties In Objects


        const [fruit, setFruit] = useState({
          color: 'red',
          name: 'apple',
        });
        
        const changeColor = (newColor) => {
          const updatedFruit = {
            ...fruit,
            color: newColor,
          };
        
          setFruit(updatedFruit);
        };
      

Removing Properties In Objects

Properties in an object can be removed by using destructuring.

Removing Properties In Objects


        const [fruit, setFruit] = useState({
          color: 'red',
          name: 'apple',
        });
        
        const removeColor = () => {
          // `rest` is an object with all the properties
          // of fruit except for `color`.
          const { color, ...rest } = fruit;
        
          setFruit(rest);
        };