Hook me up: Intro to React Hooks

Jitin Maherchandani
5 min readNov 27, 2018

React hooks has taken the React community by storm. Everyone is talking about it but still most of us are not sure about what it actually is and what problems it solves.

What are hooks in programming?

First of all, before understanding hooks we need to know what does a hook mean. Below is a simple definition that seems to be fairly understandable:

Hooks are a category of function that allows base code to call extension code. This can be useful in situations in which a core developer wants to offer extensibility without exposing their code.

One usage of hooks is in video game mod development. A game may not allow mod developers to extend base functionality, but hooks can be added by core mod library developers. With these hooks, independent developers can have their custom code called upon any desired event, such as game loading, inventory updates, entity interactions, etc.

Seems fair. With that definition we can easily conclude that hooks let us:

  1. Reuse logic
  2. Provides abstraction

Now that we have understood what hooks mean in programming, we need to understand why did the React Team at Facebook came up with this new API.

It is a wide belief that React has fairly high learning curve as compared to other frameworks. The 2 problems which I think really suck in React and causes a bump in this exponential learning curve are:

  1. Confusing classes

Let’s face it. Classes are confusing. Following listed points would be all the problems which makes classes confusing to both humans and machines:

  • this binding: It took me a full read of Kyle simpson’s book “this & Object Prototypes” from YDKJS to understand what “this” means 😅.
  • Unused methods are not stripped out at compile time as its hard to tell which functions will be used.
  • If you have ever looked into the minified version of a react project file you might have noticed that component life cycle names are not minified.
  • Classes makes it hard for hot reloading to be reliably implemented.
  • While prototyping and optimising compiler to improve the performance of React components the React team found that classes encourage some patterns that make it a lot harder for compilers to optimise.

2. Giant component logic and wrapper hell

Most of the component logics reside in the life cycle methods which makes it harder to reuse logics. Say you have a simple mouse event that you want to listen to, that alone will disperse among several of your classes lifecycles, so re-using that behaviour is out of the question because the code isn’t at one place and needs to store additional data at the component instance to function. Gets worse the more side-effects you add.

Component wrapper hell

These 2 are not different problems but they are 2 symptoms of the same problems:

React doesn’t provide a stateful primitive simpler than class components

Talk is cheap! Show me the code.

So how does hooks API make stateful logics reusable across multiple components? Lets get to our favourite part, code.

Problem statement:

Given a page with huge text content we have to stick a <header> tag to the top as the user scrolls through the list. When the header fixes to the top we also need to change the title of the page.

I am going to demonstrate this using both the approaches, first one being classes and second one: hooks!!

Class and lifecycle based approach:

The following code snippet solves the given problem that we have.

Using classes

But using classes has its own downsides:

  • First of all we need to bind all the callbacks so that we can access the class context
  • We need to add and remove the event listener in component life cycle methods componentDidMount and componentWillUnmount, this makes the logic not usable across different components as it heavily depends on the component state and bindings which are at component level.

Hooks based approach

Now comes the magic part, “React Hooks”. useEffect and useState are the Hooks that we are talking about. I am going to explain both of the hooks below:

  • useState

We call it inside a function component to add a local state to it. React will preserve this state between all the re-rendering happening. useState returns a pair which has the current state value and a function that lets you update the value.

There is only one argument to useState that is the initial state. In this example given above, the initial state is text I am not a fixed header :( .Note that unlike this.state, the state here doesn’t have to necessarily be an object — however it can be an object if you want.

Note: Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside React classes — they let you use React without classes.

  • useEffect

The useEffect hook gives you an ability to add side effects from a functional component like making an API call, adding, removing callbacks, setting state etc. The function passed to useEffect fires after layout and paint, during a deferred event. Although useEffect is deferred until after the browser has painted, it’s guaranteed to fire before any new renders. React will always flush a previous render’s effects before starting a new update.

Custom Hooks based approach

We can extract the hook logic to a separate function such that its reusable across multiple components. I have extracted the logic to a custom hook useScrollListner . This hook can be imported to any functional component enabling this stateful logic available across multiple components.

Custom hooks implementation

Thats great. But… DEAD LIFECYCLES?

render: This is the function component body itself.

componentDidMount, componentDidUpdate, componentWillUnmount: The useEffect can express all combinations of these.

shouldComponentUpdate: React.memo

constructor: Function components don’t need a constructor. You can initialise the state in the useState call. If computing it is expensive, you can pass a function to useState.

Only componentDidCatch and getDerivedStateFromError doesn’t have any Hook equivalents but React team are planning to add them eventually.

Some important Rules

There are two main rules which we should follow before using hooks:

  • Only call Hooks at the top level. Don’t try to call Hooks inside loops, conditions, or nested functions.
  • Only call Hooks from React function components. Don’t try to call Hooks from regular JavaScript functions.

This was just an intro to hooks. Following are links to the RFC and FAQ’s for hooks. Thanks for reading :)

📝 Read this story later in Journal.

🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: Get the noteworthy newsletter >

--

--