React Hooks, Part 1

a functional journeyNow That I Have Your Attention, Let’s Learn About Hooks! Photo by Chen on UnsplashI don’t know about you but I have read many articles trying to make sense of bind/call/apply in React class components and the information is just not…


This content originally appeared on Level Up Coding - Medium and was authored by Shelby Talbert

a functional journey

Now That I Have Your Attention, Let’s Learn About Hooks! Photo by Chen on Unsplash

I don’t know about you but I have read many articles trying to make sense of bind/call/apply in React class components and the information is just not sinking in… yet! With this in mind, I am really happy to know that React has been rather swiftly moving away from class components, and that functional components can indeed handle state/stateful logic. Enter Hooks! According to the React.js docs: “Hooks are functions that let you “hook into” React state and lifecycle features from function components.”

The core concepts of React Hooks were introduced at React Conf in 2018 by Sophie Alpert and Dan Abramov. According to Sophie Alpert (who was at that time the manager of the React core team at Facebook), “…many experienced devs tell us that the way binding and “this” work in classes is pretty confusing… classes are hard for humans… classes are also hard for machines… it’s hard to tell at compile time exactly how all the methods fit together…. classes make it harder for compilers to optimize.” So I’m not the only one having a time of it! ?

Class components are not officially being deprecated at this time so any new React dev should make sure they know the basics of class component concepts and the accompanying boilerplate code. As per Dan Abramov, “At Facebook we have tens of thousands of class components and, like you, we have no intention of rewriting them.” That being said, Hooks are becoming more and more common, plus they are really powerful and easy to learn. So let’s get started!

useState

Simply put, useState is intended to be used in place of this.setState Below is a typical example of the initial state variable declaration(s) which is the functional equivalent to state = {faved: [], searchTerm: “”}.

We use destructuring to first declare the name of our state variable and then use “set<variable>” for the functionality that will update state. (This is the convention.) The parentheses()after useState define the initial/default value of the variable:

useState in action

As you can see here, our state is broken down into individual state elements. This keeps us from accidentally overwriting our entire state object. Nice, huh? You can use useState as many times as you need within a component. You can pass that variable element to a child component as props, just as you might in a class component. And unlike class components, each state element does not have to be declared as an object literal, although it certainly can be.

Here we use our functional equivalent to this.setState. faved begins as an empty array (as per the image above) and after a bit of logic below, we setFaved to a new array value. And that’s it!

setFaved, equivalent to this.setState

useEffect

useEffect is a particularly effective (lol see what I did there?) Hook. It allows for the combined functionality of componentDidMount, componentDidUpdate and componentWillUnmount, as necessary. And just like these three lifecycle methods, it does not come into play until after the initial render of the component.

Again, according to the React.js docs: “The Effect Hook, useEffect, adds the ability to perform side effects from a function component… We call these operations “side effects” (or “effects” for short) because they can affect other components and can’t be done during rendering… By using this Hook, you tell React that your component needs to do something after render.”

The equivalent to componentDidMount is very simple to employ with useEffect. Just pass it through with an arrow function (which allows for the async nature of the action), and invoke the necessary function. Below, getFlowers is a simple GET fetch function which I had passed as props from my redux “mdp” (mapDispatchToProps).

functional equivalent to componentDidMount

For the componentDidUpdate functionality: you can pass an empty array as a second argument which will tell React not to check for any changes (or diffs) in state elements before re-rendering. If for instance we had a state variable of likes, and you added [likes] to the second argument passed above, useEffect would then know to skip the re-render if the likes value has not changed.

useEffect also allows us the option of telling the component how to “clean up” by passing a second function. (Note that the functions passed through can be named functions or anonymous arrow functions. Both will work inside of useEffect.) Below is a helpful example from the React.js docs.

useEffect(() => {    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);

return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});

In the example above, the API unsubscribes from the friend status before the next re-render, which is important because with each re-render, we experience a new/different instance of useEffect. If the friend.id was different in the next rendering of the component, we could see an error.

Custom Hooks!

There are plenty of rules that go along with learning Hooks. One of which is not to use Hooks nested within functions. However there is a big loophole: custom Hooks! You can write your own custom Hook by naming ituse<SomeFunction>. (The React linter will know that you are writing your own custom Hook and will refrain from dinging you with an error message.) In this case you can add useState, useEffect or other Hooks (which I plan to write about as soon as I learn them myself!) and group them together within one function. For an effective example of a custom Hook (I am still learning so have not implemented one in my own apps), go here.

Refactoring

If you decide to take a stab at refactoring a class component into a functional one with Hooks, know that you won’t have to refactor the entire app. A React app can work perfectly well with some class components and other functional components using Hooks.

IMPORTANT: you must import any utilized Hooks or your code will break

Note: do remember when refactoring a class component to functional one, we have to write let, const (or var) back into our declared functions. Remove all references to this and state. Pass props in the functional component if we are passing props. (Feel free to destructure those props if you’d like.) Don’t forget to remove therender() {}! Let any linter/browser error messages lead your way.

Best of luck with refactoring. Let me know how it goes!!


React Hooks, Part 1 was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Shelby Talbert


Print Share Comment Cite Upload Translate Updates
APA

Shelby Talbert | Sciencx (2021-04-13T12:57:14+00:00) React Hooks, Part 1. Retrieved from https://www.scien.cx/2021/04/13/react-hooks-part-1/

MLA
" » React Hooks, Part 1." Shelby Talbert | Sciencx - Tuesday April 13, 2021, https://www.scien.cx/2021/04/13/react-hooks-part-1/
HARVARD
Shelby Talbert | Sciencx Tuesday April 13, 2021 » React Hooks, Part 1., viewed ,<https://www.scien.cx/2021/04/13/react-hooks-part-1/>
VANCOUVER
Shelby Talbert | Sciencx - » React Hooks, Part 1. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/13/react-hooks-part-1/
CHICAGO
" » React Hooks, Part 1." Shelby Talbert | Sciencx - Accessed . https://www.scien.cx/2021/04/13/react-hooks-part-1/
IEEE
" » React Hooks, Part 1." Shelby Talbert | Sciencx [Online]. Available: https://www.scien.cx/2021/04/13/react-hooks-part-1/. [Accessed: ]
rf:citation
» React Hooks, Part 1 | Shelby Talbert | Sciencx | https://www.scien.cx/2021/04/13/react-hooks-part-1/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.