A Quick Introduction to Hooks in ReactJS

Berkay Yıldız
Frontend Weekly
Published in
3 min readFeb 9, 2019

--

Hooks was introduced in React Conf in September 2018. It has attracted a lot of attention, and I was waiting for stable release. Finally, It published in 16.8 version.

What are the Hooks?

Basically, it provides functionality to use the state in function components. Let’s explain this with an example, assume that you have a popover component and visibility of this component is managed externally. Polaris’ component can be a good example.

If we develop this component with classical methods, first of all, we have to create a React component, after that define state …

Now, we don’t need this, just create a simple function component and use hooks. Basically, the following code block allows this, just define an initial state and modify this state using the setState function.

I created a sandbox for this sample, you can find the codes on this box. Let’s dive into the code, in this example, I just need a boolean value, because of this, I created an expression like the following code. I set a boolean value, but you can set any type of value, and the isActive parameter is used to observe state. If you wanna change state, just call setStatus(…).

Mostly, life is not easy like this example, sometimes the state may not be just a simple value. We may have a JSON object and you may work with only a part of it. In this situation, the whole state has to be updated.

Minimalist Redux

Okay, it looks good but my state management is complex than these. No worry, they have useReducer. It basically behaves like Redux. Just create your reducer and trigger it using dispatch(…) function.

Code Source: https://reactjs.org/docs/hooks-reference.html#usereducer

In this blog post, I just tried to make a quick introduction to give an idea. This is the visible part of the iceberg. There are a lot of helper functions like this. I strongly recommend to watch Dan Abramov’s presentation and read the React’s official documentation.

Source

--

--