I've always loved React. It's been my favorite programming language since I started working in web development.
The concept of components and state was easy to wrap my brain around, and made sense to me. Building these components and having them interact with each other is like creating your own Lego blocks to build a website.
State management has gone through many forms since React was released in 2016, from helper functions in ComponentDidUpdate and ComponentDidMount, to the current evolution of functional components and hooks making waves in the react community.
I'm always excited to try a new pattern for developing components, and diving into hooks has been a very rewarding experience. I’m here to provide some examples of why you should adopt them and why they are all the rage these days.
What is the problem hooks are trying to solve?
1. Providing a pattern for handling state
2. Cutting down on code while still maintaining, and even expanding on, the capabilility of functional React Components
3. Giving functional components access to state previously only accessible through class components
That last one, functional components, is a direct line into a much larger React conversation. A line, taken straight from the hooks FAQ, reads “hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.”
Why?! Might you ask. This article by David Joch, written in 2018, provides insight into the battle between State vs Functional components. The decision to choose between these two types of components are your call. But functional components are more fun. And You get to use hooks. Which are also fun.
Alright, enough backstory, now practical hooks in practice.
In the introductory example of hooks, `useState` is imported from React ( make sure its 16.8 and above) and initialized with two constants, `count` and `setCount`. As a rule, useState takes the initial value of the state as an argument. It always returns a pair of values, the current state and a function that updates it. This means there’s only two things to think about. A variable to be used anywhere and a very simple updating method.
Also, a thing to note is you don’t have to use the variable inside the updating function. This is shown in the example below:
You can create several state variables inside the functional component by repeating the useState function, or you can also roll all of your variables into one `state` object (which is fun and saves lines!)
And there you have it, running functional components with hooks! Fun times!