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 here https://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 here https://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)