Introduction to React Hooks
Giving superpowers to functional
components
From React’s version 16.8.0, Hooks are
introduced to make functional components
more useful.
Class Vs Function
In React, class components are stateful and
smart, being state is attached to it and kept
persistent through renders. Then functional
components were stateless and dumb
components, having nor state nor logic
attached to it. state in it, and just used to break
down complex components into segments.
Class Vs Function
As an example, class component can have
state, and it could be manipulated using
lifecycle methods such as constructor,
componentDidMount and such. However,
functional component only accepts props from
its parent, and renders accordingly. It wouldn’t
keep internal state value, that would be
persistent through renders, but rather renders
according to whatever passed through props
Class Vs Function
In complex React application, there is parent
class component keeping track of state, and
manipulate state according to business logic.
Afterwards child functional components are
passed props, and used only for rendering
purpose. These wouldn’t have any persistent
state in it, and just used to break down complex
components into segments.
Like
<DigitalWatch>
Parent class component with state, and
business logic to count time.
→ <TimeView time={this.state.time}>
Child functional component only with props and
just rendering props.
Hooks
React Hooks enable functional components to
attach local state with it, and React will
preserve this state between re-renders.
Thereby this will allow React to be used without
classes.
●
However, we often can’t break complex
components down any further because the logic
is stateful and can’t be extracted to a function or
another component.
Hooks
Let's get started with hooks
state Hook
import React, { useState } from 'react';function Example() {
const [count, setCount] = useState(0);return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Add </button>
<button onClick={() => setCount(count - 1)}> Remove </button>
</div>
);
}