React Hooks Tutorial for Beginners

Rishabh Srivastava
3 min readMay 9, 2021

--

What you will learn

In the following tutorial you’ll learn:

  1. How to use React Hooks

What is hooks:

“Hooks are a new addition to React in version 16.8 that allows you use state and other React features, like lifecycle methods, without writing a class.”

So hooks were introduced to implement lifecycle methods and states in functional components. They also bought the idea of code reusability along with them, that’s why it was so quickly accepted within the React Community

The first most important react hooks:

useState hook

This hook helps us to use and maintain a state within the functional component. It’s is very easy to use. It is a function, you’ll import it in your component as:

After importing you will destructure two value of it:

The argument passes in the useState is actually the initial state. Here we have a buttonText as the state variable and the setButtonText as the function update that modifies the state variable.

So in the previous example the a button component will become hooks:

Fetching the data with useEffect:

useEffect serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

It contains a callback and a dependencies array. The hook will run every time when any of the values in the dependencies array changes. When the array is empty, the effect runs only once.

One more thing used in this hook is the cleanup function, which runs when we return a function in the callback. This function helps in cleaning of side effects i.e clearing a timer, closing a web socket, etc.

custom React hook

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks

Custom hooks means fewer keystrokes and less repetitive code.

This is how you would use the custom hook:

And finally we have a clean, nice and better way for sharing logic

That’s it for now. There are other hooks too like useRef, useCallback but they are rarely used. Thanks for reading this article. Let me know if anything is not clear.

There are a lot of other resources out there for learning React hooks. Here are my suggestions:

Happy Coding!

--

--

No responses yet