Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

K-Sato
K-Sato

Posted on • Edited on

     

React hooks for noobs

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 usestate 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 componentusinguseState to the equivalentclass component.

Equivalent Class Component

It does the following 2 things.

  • (1) Define thecount state and its initialState0.
  • (2) Add 1 tocount 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>);}}
Enter fullscreen modeExit fullscreen mode

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);
Enter fullscreen modeExit fullscreen mode

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)}
Enter fullscreen modeExit fullscreen mode

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 usecount directory!(no need to dothis.count.)
  • (2) You can update the state by usingsetCount.
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;
Enter fullscreen modeExit fullscreen mode

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;
Enter fullscreen modeExit fullscreen mode

Effect Hook

You can perform side effects in functional components by using a hook calleduseEffect!

Let's see how to useuseEffec through comparing afunctional componentusinguseEffect to the equivalentclass component.

Example Class Component

In class components, we perform side effects such as fetching data and changing the DOM incomponentDidMountcomponentDidUpdate.

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>);}}
Enter fullscreen modeExit fullscreen mode

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>);}
Enter fullscreen modeExit fullscreen mode

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 calledStatus which returnsLogged in if it receivesid = 1.
  • (2) A component calledMessage 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></>)}
Enter fullscreen modeExit fullscreen mode
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></>)}
Enter fullscreen modeExit fullscreen mode

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;}
Enter fullscreen modeExit fullscreen mode

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></>)}
Enter fullscreen modeExit fullscreen mode
importReactfrom'react';importuseLogInfrom'./useLogIn';exportdefaultfunctionMessage(props){constmessage=useLogIn(props.user.id)?'Welcome Back':'Who are you??'return(<><h1>Message:{message}</h1></>)}
Enter fullscreen modeExit fullscreen mode

Thecustom hooks can be used for other cool stuff, check out the official document aboutBuilding Your Own Hooks.

Resources

Top comments(13)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
scriptkavi profile image
ScriptKavi
Crafting Digital Experiences with Precision and Creativity.Current Craft → http://hooks.scriptkavi.com - https://vedvyas.io
  • Location
    Bengaluru
  • Joined

Many early birds have already started using this custom hooks library
in their ReactJs/NextJs project.

Have you started using it?

scriptkavi/hooks

PS: Don't be a late bloomer :P

CollapseExpand
 
cryptoexchangesoftware profile image
Shah Iritza
Irtiza is the director at Crypto Exchange Software, he has been working as a Software developer and an IT expert for 5 years. He started his own company for Crypto Software Development.
  • Location
    California
  • Work
    Director 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.

CollapseExpand
 
samparker4123 profile image
samparker4123
  • Joined

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.

CollapseExpand
 
elmadavis profile image
elmadavis
A Web Developer
  • Location
    London, UK
  • Joined
• Edited on• Edited

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.

CollapseExpand
 
itsliamwilliam profile image
itsliamwilliam
  • Joined

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.

CollapseExpand
 
samtim2050 profile image
samtim2050
  • Joined

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.

CollapseExpand
 
markbuttler profile image
markbuttler7164
  • Joined

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.

CollapseExpand
 
arthur_d9cbaea803a9c8d582 profile image
Arthur
  • Joined
• Edited on• Edited

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!

CollapseExpand
 
sergiogomesva profile image
Sérgio Gomes
  • Location
    Porto
  • Work
    Software Engineer at Farfetch
  • Joined

Simple and succinct. Well done!

CollapseExpand
 
cameron_luka_dbf4b1916640 profile image
Cameron Luka
  • Joined

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!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer
  • Work
    Software Engineer
  • Joined

More fromK-Sato

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp