React Hooks - a Practical Usage of useEffect
Overview
React Hooks isn't a new thing, however there's still a lot 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.
< check the original gist />
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.
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.
The <Menu> is getting Three props - items, discountedItems 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 immediately 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 ingredient), 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>.
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 conditionally 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.
< check the original gist />
Still have some questions?
Write me to nadav@nsoft.co.il
Nadav Lebovitch
Web Development Consultant
CEO & CTO at nSoft
תודה רבה לך על השיתוף🙂 אני מזמין אותך לקבוצה שלי: הקבוצה מחברת בין ישראלים במגוון תחומים, הקבוצה מייצרת לקוחות,שיתופי פעולה ואירועים. https://chat.whatsapp.com/IyTWnwphyc8AZAcawRTUhR
תודה רבה לך על השיתוף החשוב🙂 אני מאוד אשמח לראות אותך בקבוצה שלי: https://chat.whatsapp.com/HWWA9nLQYhW9DH97x227hJ
תודה רבה על השיתוף! אני מזמין אותך לקבוצה שלי שמחברת בין ישראלים לשאר העולם במגוון נושאים מטרת הקבוצה לשתף מידע, לשאול שאלות וליצור שיתופי פעולה: https://chat.whatsapp.com/BubG8iFDe2bHHWkNYiboeU