Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Carl McIntosh
Carl McIntosh

Posted on

     

My First React Custom Hook

Premise

I've created a simple counter in React that increases and decreases a number, using the useState hook in React to pass down props to the buttons. I wanted to create a hook that showed the previous total to the user

It uses useRef() to store the current value. This is then placed inside a variable. The useRef hook returns an object with one property (current) You can read more about useRef herehttps://reactjs.org/docs/hooks-reference.html#useref

usePreviousTotal
code

I've also used a useEffect hook as I'm reaching inside the DOM to grab the current value, this is stored in the dependancy array as I only want to render this when that value changes. You can read more about useEffect herehttps://reactjs.org/docs/hooks-effect.html

Now all that is left is to import the hook into the app.

hook
And that's it. Look more at the React docs for more information.

counter

Top comments(0)

Subscribe
pic
Create template

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

Dismiss

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

Hi, I'm Carl. I'm a Software Developer currently enrolled on the 4th cohort on the School of Code.
  • Location
    Birmingham, England
  • Work
    Student @ the School of Code at Student
  • Joined

Trending onDEV CommunityHot

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