Story
Today in the morning, I went to the nearest ATM machine to withdraw some money. As usual, I entered the amount and pushed the button. Then it asked me, “Do you want to withdraw any more amount?” My answer was no. Again, it asked me, “Do you want to get a receipt?” My answer was no. Then I picked up the money and purchased some household items from the local market. A very usual story for all of us, right?
But when I was coming home, I realized it works like React side effects. When I pushed the button just to withdraw money, that was kind of like a pure function. However, the machine, or the server, or the system wanted to provide me some extra, additional information like balance info, receipt, next withdrawal option, and sending a message to my phone. These are side effects, because they happen outside of my original input.
Then I realized, nothing is outside of our life. Everything is deeply connected. Especially programming—it’s inevitably involved in our life. Maybe that’s one of the reasons I love it so much. Thank you for reading my today's small story. Hope you feel the same way. :)
React Side Effects Explained
Let’s break it down technically:
- Pure Functions: Just like entering an amount in the ATM, a pure function in React always produces the same output for the same input and does not affect anything outside its scope.
- Side Effects: Any additional operations happening outside the main function—like checking balance, printing receipt, sending notifications—are side effects. In React, this is similar to what happens inside
useEffect(). - useEffect Hook: React provides
useEffectto manage side effects like API calls, DOM updates, timers, or subscriptions that occur as a result of rendering. - Life Analogy: Just like ATM actions are interconnected with notifications and other outputs, in React, side effects are unavoidable and part of a larger system. Managing them properly ensures smooth behavior and predictable outcomes.
Key Takeaways
- Always separate pure functions from side effects for better maintainability.
- Use
useEffectin React to handle operations that affect things outside of the component's return value. - Understanding side effects helps you write more predictable and bug-free React applications.
- Seeing everyday life analogies can make complex programming concepts more relatable and easier to understand.