Introduction
Hooks
are a new feature introduced in React16.8.
I'll try to explain what they are in the following order.
What are Hooks?
According to the official React documentation,
Hooks let you use state and other React features without writing a class.
Yup. That's exactly it!.
Now you can use some React features such asstate
in functional components thanks tohooks
!!
I'll introduce 3 following hooks in this post.
- (1)State Hook: It lets you use
state
andsetState
in functional components. - (2)Effect Hook: It lets you perform side effects such as data fetching in functional components.
- (3)Custom Hooks: Building your custom hooks lets you extract component logic into reusable functions.
Rules of Hooks
There are 2 ground rules you have to follow to use hooks safely.
(1) Only Call Hooks at the Top Level!!
Don’t call Hooks inside loops, conditions, or nested functions.
(2) Only Call Hooks from React Functions!!
Don’t call Hooks from regular JavaScript functions.
State Hook
You can usestate
andsetState
in functional components by using a hook calleduseState
.
Let's see how to useuseState
through comparing afunctional component
usinguseState
to the equivalentclass component
.
Equivalent Class Component
It does the following 2 things.
- (1) Define the
count
state and its initialState0
. - (2) Add 1 to
count
each time setState is called.
classExampleextendsReact.Component{constructor(props){super(props);this.state={count:0};}render(){return(<div><p>You clicked{this.state.count} times</p><buttononClick={()=>this.setState({count:this.state.count+1})}> Click Me</button></div>);}}
Functional Component with State Hook
Now it's time to create a functional component usinguseState
which does the same thing as the class component above.
The basic syntax ofuseState
looks like this!
const[state,setState]=useState(initialState);
It's like you define thestate
,setState
andinitialState
all together.
If you want to define the same state as the one in the class component above, it would look like this.
importReact,{useState}from'react';functionCounter(){const[count,setCount]=useState(0)}
Notice 3 things in the code above!
- (1)
count
is the equivalent ofthis.state={count:0}
in the class component. - (2)
setCount
is the equivalent ofsetState
part in the class component. - (3)
0
is the initial state ofcount
.
While you are writing up the rest of the code, keep these 2 things in mind.
- (1) You can use
count
directory!(no need to dothis.count
.) - (2) You can update the state by using
setCount
.
importReact,{useState}from'react';functionCounter(){const[count,setCount]=useState(0)return(<div> // (1) You can use count directory!<p>You clicked{count} times</p> // (2) You can update the state by using setCount.<buttononClick={()=>setCount(count+1)}> Click me</button></div>)}exportdefaultCounter;
As a side note, you can define multiplestates
like the code below.
importReact,{useState}from'react';functionCounter(){const[count,setCount]=useState(0)const[name,setName]=useState('')return(<div><p>You clicked{count} times</p><buttononClick={()=>setCount(count+1)}> Click me</button><p>My name is{name}.</p><buttononClick={()=>setName('テスト太郎')}>Show my name</button></div>)}exportdefaultCounter;
Effect Hook
You can perform side effects in functional components by using a hook calleduseEffect
!
Let's see how to useuseEffec
through comparing afunctional component
usinguseEffect
to the equivalentclass component
.
Example Class Component
In class components, we perform side effects such as fetching data and changing the DOM incomponentDidMount
componentDidUpdate
.
Here, it outputsIt did mount
in the console after a component is mounted and outputsIt did get updated
after updating occurs.
importReactfrom'react';classEffectextendsReact.Component{constructor(props){super(props);this.state={count:0};}componentDidMount(){console.log('It did mount.')}componentDidUpdate(){console.log('It did get updated.')}render(){return(<div><h1>You clicked{this.state.count} times</h1><buttononClick={()=>this.setState({count:this.state.count+1})}> Click me</button></div>);}}
Example Functional Component using useEffect
TheuseEffect
hook is like a combination ofcomponentDidMount
,componentDidUpdate
andcomponentWillUnmount
.
It runs afterevery render including the first render.
When you are building react applications withhooks
this is where you perform side effects.
importReact,{useState,useEffect}from'react'functionEffect(){const[count,setCount]=useState(0)useEffect(()=>{console.log('It got rendered')})return(<div><h1>You clicked{count} times</h1><buttononClick={()=>setCount(count+1)}> Click me</button></div>);}
Custom Hooks
As I mentioned above, building your custom hooks lets you extract component logic into reusable functions.
Let's suppose there are two components like below.
- (1) A component called
Status
which returnsLogged in
if it receivesid = 1
. - (2) A component called
Message
which returnsWelocme Back
if it receivesid = 1
.
exportdefaultfunctionStatus(props){const[isLoggedIn,setIsLoggedIn]=useState(false);consthandleStateChange=(id)=>{if(id===1){setIsLoggedIn(true)}else{setIsLoggedIn(false)}}useEffect(()=>{handleStateChange(props.user.id)})conststatus=isLoggedIn?'Logged in':'Sign up'return(<><h1>Status:{status}</h1></>)}
exportdefaultfunctionMessage(props){const[isLoggedIn,setIsLoggedIn]=useState(false);consthandleStateChange=(id)=>{if(id===1){setIsLoggedIn(true)}else{setIsLoggedIn(false)}}useEffect(()=>{handleStateChange(props.user.id)})constmessage=isLoggedIn?'Welcome Back':'Who are you??'return(<><h1>Message:{message}</h1></>)}
As you probably noticed, it's very redundant.
You can build acustom hook
to extract the same logic exists in both components into one reusable function.
※It is very important that you name your custom hook starting withuse
.
In this case, I named my custom hookuseLogIn
.
import{useState,useEffect}from'react';exportdefaultfunctionuseLogIn(userId){const[isLoggedIn,setIsLoggedIn]=useState(false);// The login you want to reuse.consthandleStateChange=(id)=>{if(id===1){setIsLoggedIn(true)}else{setIsLoggedIn(false)}}// Perform side effects in useEffect.useEffect(()=>{handleStateChange(userId)})returnisLoggedIn;}
UsinguseLogIn
, we can simplifyStatus
andMessage
components.
importReactfrom'react';importuseLogInfrom'./useLogIn';exportdefaultfunctionStatus(props){conststatus=useLogIn(props.user.id)?'Logged in':'Sign up'return(<><h1>Status:{status}</h1></>)}
importReactfrom'react';importuseLogInfrom'./useLogIn';exportdefaultfunctionMessage(props){constmessage=useLogIn(props.user.id)?'Welcome Back':'Who are you??'return(<><h1>Message:{message}</h1></>)}
Thecustom hooks
can be used for other cool stuff, check out the official document aboutBuilding Your Own Hooks.
Resources
Top comments(13)

- LocationBengaluru
- Joined
Many early birds have already started using this custom hooks library
in their ReactJs/NextJs project.
Have you started using it?
PS: Don't be a late bloomer :P

- LocationCalifornia
- WorkDirector at Crypto Exchange Software
- Joined
The new feature in the react 16.8 version, it is used to allow and use state and other features of React with out writing or giving a class. I have experienced this when I used this to my siteperfectcvmaker.ae last month and it is great and easy to make.

To run the code in Java, you must first create a class. I'm not sure what this Hook technique is all about. I'm working on an application for my Malaysian customer ofTransfer Factor Malaysia. I'm completely baffled as to how to do this approach. I attempted it without first establishing a class. Errors were still present.

Java always requires a class to run the code. I didn’t get a clear concept of this Hook method. I am developing an application for my clientcv help uk - cvwritings.co.uk. I am totally getting confused about how to run this method. I’ve tried it without creating a class. It was still showing errors.

These are extraordinary in light of the fact that going out as a family can be very costly, particularly at the motion pictures where food and beverages are difficult to bear on an ordinary financial plan. By :UK Essay Writing Service.

It's a new feature in React that allows you to leverage state and other React capabilities without having to write or give a class. Last month, I utilised this on mybest travel company site, and it worked excellent and was simple to set up.

The best thing is that the custom hooks can be used for other cool stuff. Thanks for sharing this guide. This will be helpful for me to serve theanimation production service all over the region.

As a noob developing a site, these hooks helped me out in understanding complex functions, which is a headache for me. I am working on aWikipedia services site, which is a real problem. I am facing other problems too if someone can help me out!

This guide on React hooks is incredibly helpful! I’m planning to use these hooks on my site,WikipediaPageCreations.com, and I know they’ll make a big difference. Thanks for sharing such a clear and practical explanation!
For further actions, you may consider blocking this person and/orreporting abuse