
Hooks Introduction
Hooks are a new feature introduced in React 16.8. They provide an alternative to writing class-based components, and an alternative to state management and lifecycle methods in React. Hooks don't work inside Class Components.
Benefits of Using Hooks
Hooks provide a better of writing code as they reduce the complexity of components. They make our
code more readable, concise and clear, and reduce the code. Another great thing about hooks is that
you no longer have to deal with the this
keyword, as it confuses alot of programmers.
Some of the pre-requisites for using Hooks are:
- Node Version 6 or above
- NPM Version 5.2 or above
- Create-react-app tool
Motivation behind using Hooks
Hooks solve a wide range of unconnected problems that have been faced over the last few years. Hooks allow the reuse of stateful logic without changing the component's hierarchy. This makes it pretty easy to share Hooks among multiple components. On the other hand, having this functionality in class components was quite complex.
Classes can make things complex when it comes to large components. How have to understand how this
works in javascript, which is completely different from how it works in other languages. You always have to bind the event handlers in order to have the methods working properly.
Built-in Hooks
The built-in hooks are divided into two categories, listed below:
Basic Hooks- useState
- useEffect
- useContext
- useReducer
- useCallback
- useMemo
- useRef
- useImperativeHandle
- useLayoutEffect
- useDebugValue
Here's an example of the state Hook:
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
We'll be covering about the state Hook in detail in the next tutorial.