Learn the basics of React Hooks in <10 minutes

const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1) } return ( <div> <h3 className="center">Welcome to the Counter of Life </h3> <button className="center-block" onClick={handleClick}> {count} </button> </div> ); }There are a few things to note here, apart from the obvious simplicity of the code!One, since invoking useState returns an array of values, the values could be easily destructed into separate values as shown below:const [count, setCount] = useState(0);Also, note how the handleClick function in the refactored code doesn’t need any reference to prevState or anything like that.

It just calls setCount with the new value count + 1.

const handleClick = () => { setCount(count + 1) }This is because of the correct value of the count state variable will always be kept across re-renders.

So, need to update count state variable, just call setCount with the new value e.


setCount(count + 1)Simple as it sounds, you’ve built your very first component using hooks.

I know it’s a contrived example, but that’s a good start!Multiple useState callsWith class components, we all got used to set state values in an object whether they contained a single property or more.

// single property state = { count: 0}// multiple properties state = { count: 0, time: '07:00'}With useState you may have noticed a subtle difference.

In the example above, we only called useState with the actual initial value.

Not an object to hold the value.

useState(0)So, what if we wanted to another state value?Can multiple useState calls be used?Consider the component below.

Same as before but this time it tracks time of click.

As you can see, the hooks usage is quite the same, except for having a new useState call.

const [time, setTime] = useState(new Date())Now time is used in the rendered JSX to retrieve the hour, minute and second of the click.

<p className="center"> at: { `${time.

getHours()} : ${time.

getMinutes()} : ${time.

getSeconds()}`}</p>Great!However, is it possible to use an object with useState as opposed to multiple useState calls?Absolutely!If you choose to do this, you should note that unlike setState calls, the values passed into useState replaces the state value.

setState merges object properties but useState replaces the entire value.

The Effect HookWith class components you’ve likely performed side effects such as logging, fetching data or managing subscriptions.

These side effects may be called “effects” for short, and the effect hook, useEffect was created for this purpose.

How’s it used?Well, the useEffect hook is called by passing it a function within which you can perform your side effects.

Here’s a quick example.

useEffect(() => { // ????.you can perform side effects here console.

log("useEffect first timer here.

")})To useEffect I’ve passed an anonymous function with some side effect called within it.

The next logical question is, when is the useEffect function called?Well, remember that in class components you had lifecycle methods such as componentDidMount and componentDidUpdate.

Since functional components don’t have these lifecycle methods, useEffect kinda takes their place.

Thus, in the example above, the function within useEffect also known as the effect function, will be invoked when the functional component mounts (componentDidMount) and when the component updates componentDidUpdate).

Here’s that in action.

By adding the useEffect call above to the counter app, here’s the behavior we get.

NB: The useEffect hook isn’t entirely the same as componentDidMount + componentDidUpdate.

It can be viewed as such, but the implementation differs with some subtle differences.

It’s interesting that the effect function was invoked every time there was an update.

That’s great, but it’s not always the desired functionality.

What if you only want to run the effect function only when the component mounts?That’s a common use case an useEffect takes a second parameter, an array of dependencies to handle this.

If you pass in an empty array, the effect function is run only on mount — subsequent re-renders don’t trigger the effect function.

useEffect(() => { console.

log("useEffect first timer here.

")}, []) If you pass any values into this array, then the effect function will be run on mount, and anytime the values passed are updated.


e if any of the values are changed, the effected call will re-run.

useEffect(() => { console.

log("useEffect first timer here.

")}, [count]) The effect function will be run on mount, and whenever the count function changes.

count changes when the button is clicked, so the effect function re-runsWhat about subscriptions?It’s common to subscribe and unsubscribe from certain effects in certain apps.

Consider the following:useEffect(() => { const clicked = () => console.

log('window clicked'); window.

addEventListener('click', clicked);}, [])In the effect above, upon mounting, a click event listener is attached to the window.

How do we unsubscribe from this listener when the component is unmounted?Well, useEffect allows for this.

If you return a function within your effect function, it will be invoked when the component unmounts.

This is the perfect place to cancel subscriptions as shown below:useEffect(() => { const clicked = () => console.

log('window clicked'); window.

addEventListener('click', clicked); return () => { window.

removeEventListener('click', clicked) } }, [])There’s a lot more you can do with the useEffect hook such as making API calls.

Build Your own HooksFrom the start of this article we’ve taken (and used) candies from the candy box React provides.

However, React also provides a way for you to make your own unique candies — called custom hooks.

So, how does that work?A custom hook is just a regular function.

However, its name must begin with the word, use and if needed, it may call any of the React hooks within itself.

Below’s an example:The Rules of HooksThere are two rules to adhere to while using hooks.

Only Call Hooks at the Top Level i.


not within conditionals, loops or nested functions.

Only Call Hooks from React Functions i.


Functional Components and Custom Hooks.

This ESLint plugin is great to ensure you adhere to these rules within your projects.

Other CandiesWe have considered a few of the hooks React provides, but there’s more!This introduction should have prepared you to take on the perhaps more dense documentation.

Check it out.


. More details

Leave a Reply