A practical use of useEffect

Overview

React Hooks isn’t a new thing, however there’s still alot to learn and many ways to apply them. The subject of combining different hooks such as useState and useEffect is also a point developers usually struggle with as they’re going into React Hooks.

 

A shopping list app composed using functional components

The power of Hooks comes into play especially when building slim, functional components which require managing some internal state. Hooks allow doing exactly that – without the overhead of Class components, Constructors and full lifecycle management methods.

Starting from the top

Take a look at such an app utilizing hooks for its state management.

const App = () => {
  const [items, setItems] = useState([
    { id: 1, title: 'Tomatoes' },
    { id: 2, title: 'Onions' },
    { id: 3, title: 'Cucumbers' },
    { id: 4, title: 'Olives' },
    { id: 5, title: 'Letuce' },
    { id: 6, title: 'Peanutes' },
  ]);

  const [availableItems, setAvailableItems] = useState([1, 2, 4, 6]);

  const discountedItems = [
    { id: 1, percentage: 30 },
    { id: 6, percentage: 10 },
  ];

  const addItem = () => {
    const id = items.slice(-1)[0].id + 1;
    const newItems = [...items, { id, title: `Ingredient #${id}` }];
    setItems(newItems);
    const newAvailItems = [...availableItems, id];
    setAvailableItems(newAvailItems);
  };

  return (
    <div className="App">
      <h1>Pick ingredients for your salad:</h1>
      <Menu
        items={items}
        availableItems={availableItems}
        discountedItems={discountedItems}
      />
      <div>
        <button onClick={addItem}>Add Item</button>
      </div>
    </div>
  );
}

 

The App holds a list of items – these are Salad ingredients – Let’s say we got them from the server etc. It also holds a list of availableItems and discountedItems.

It’s rendering <Menu> component to display the items and allows the user to tick / untick items. Through the addItem method The user can also add an item / ingredient. For the sake of the example each new ingredient has an autogenerated title.

The app is using the useState hook twice – first to manage the list of Items and then to manage the list of Available Items as a new item is added and becomes available.

 

A peek under the hood

So far that was the everyday use of setState. Let’s take a look at the internal components – Menu and its children.

const Menu = ({ items, discountedItems, availableItems }) => {
  const [activeItems, setActiveItems] = useState([]);
  const [ingredients, setIngredients] = useState([]);

  useEffect(() => {
    const newIngredients = items.map(item => {
      // Check if item is available. Return true or false
      const isAvailable = availableItems.indexOf(item.id) > -1;

      if (isAvailable) {
        // Check if item is discounted. If so, return the discount
        const discount = discountedItems.find(disItem => disItem.id === item.id);

        return { ...item, discount: discount && discount.percentage };
      }

      return false;
    }).filter(i => i);
    setIngredients(newIngredients);
  }, [items]);

  const toggleItem = (item, { target: { checked } }) => {
    // Remove the toggled item from the array
    const newActiveItems = activeItems.filter(i => i !== item.id);

    if (checked) {
      // If item is checked, add the toggled item to the array
      newActiveItems.push(item.id);
    }

    // Set the new activeItems array
    setActiveItems(newActiveItems);
  }

  return (<ItemsList
    items={ingredients}
    activeItems={activeItems}
    toggleItem={toggleItem} />);
}

 

The <Menu> is getting Three props – itemsdiscountedItems and availableItems. In order to render its child, <ItemsList>, which only gets item and activeItems props, the <Menu> component has to merge its props into a single ingredients variable to pass onto <ItemsList>. This is done using the useEffect hook, which runs the unification logic and then calls setIngredients to persist it in the state.

What’s this array at the second argument of useEffect?

useEffect does what it says – creates side effects. This makes it a key lifecycle method which has to play well with the rendering cycle of the component. We don’t necessarily want useEffect to run on every render of our component. This second argument of useEffect helps doing just that.

The basics for this are:

  • no second argument – the effect will run every time the component renders (similar to componentDidUpdate, only it runs during the first render as well).
  • empty array – the effect will run just once (similar to componentDidMount).
  • non-empty array – the effect will run only when the array’s variable have changed (similar to using a condition in componentWillRecieveProps).

In our example the effect gets [items] as the second argument, corresponding to the 3rd use case above. This means whenever the items prop is modified, our effect will run.

Why do we need this?

As we’re updating the component’s state inside the effect (by calling setIngredients), we cannot simply omit the second argument as we’ll immediatly go into an infinite loop – similar to calling setState inside componentDidMount with no conditions (that’s a no-no!). And as we’d like the effect to run whenever items is modified (user adds a new ingerdient), we cannot supply an empty array as the effect will then run only once.

Let me see some UI

Finally, the core part of our UI is rendered by Two final components – <ItemsList> which renders <MenuItem>.

const ItemsList = ({ items, activeItems, toggleItem }) => (
  <Fragment>
    <div>Checked Items</div>
  <ul>{items.filter(item => activeItems.indexOf(item.id) > -1).map(item =>
      <li>
        <MenuItem
          item={item}
          checked
          onChange={e => toggleItem(item, e)}
        />
      </li>)
    }</ul>
  <div>Available Items</div>
  <ul>{items.filter(item => activeItems.indexOf(item.id) === -1).map(item =>
      <li>
        <MenuItem
          item={item}
          checked={activeItems.indexOf(item.id) > -1}
          onChange={e => toggleItem(item, e)}
        />
      </li>)
    }</ul>
  </Fragment>
);

const MenuItem = ({ item, checked, onChange }) => (
  <Fragment>
    <input
      key={item.id}
      type="checkbox"
      checked={checked}
      onChange={onChange} />
    <span>{item.title}</span>
    {item.discount && <span style={{ color: 'red' }}> [-{item.discount}%]</span>}
  </Fragment>);

 

These Two components are what we used to call “dumb” components – they’re stateless and only rendering some UI, passing any events to their props.

Summary

  • We went through a composition of functional components, some manage their own state and some don’t have any.
  • We learned the different cases of useEffect (But check the official docs for more goodies and gotachs).
  • We combined Two effects to achieve our goal of conditionaly changing the state on props change.

Hooks can really make your components lighter and much more testable, thus your app more maintainable. However you should know your way around them to make the best use of those and avoid common mistakes.

Drop your info here

X

Like what you see?

Sign up to our newsletter to get more tips,
best practices and helpful solutions
straight out from our own experience in the Front-end world.

We won’t spam you and won’t sell your email to nobody. Scouts promise!

X