React Hooks Mini Crash Course

chrisachard

Chris Achard

Posted on August 30, 2019

React Hooks Mini Crash Course

This was originally posted as a Twitter thread: https://twitter.com/chrisachard/status/1167132279333957632

Want to learn hooks, but you've been too busy? ā²

šŸ”„ Here's a mini crash course just for you! šŸ”„

(code links at the end)

1.

Add state to function components by calling useState and pass in the initial value.

useState in function components

2.

useState returns 2 values in an array:

  1. the current value of the state
  2. a function to update the state

useState

3.

Call hooks at the top level of a function, and NOT in if statements or loops.

This is required for React to internally keep track of the hook values.

call hooks at the top level

4.

Perform asynchronous actions and actions with side effects in the useEffect hook

That way, async actions still work across multiple renders

useEffect

5.

useEffect takes an array of dependencies as the second argument

THIS IS IMPORTANT! Skipping the dependency list can result in infinite loops, or code that doesn't run when you think it should

useEffect dependencies

6.

Write custom hooks as function that start with the word use

Then use any built in hooks you want

and return (or not) and values and functions

Custom Hooks

7.

There are many other built in hooks, but they all follow similar patterns

Get the complete list here: https://reactjs.org/docs/hooks-reference.html

8.

That's it! You can now add state and long-running effects to function components.

Class components aren't dead, but hooks do help clean up some component logic.

9.

Here are links to code you can try out!

useState

useEffect

Custom Hooks

Ā 

Like this post?
You can find more by:

Thanks for reading!

šŸ’– šŸ’Ŗ šŸ™… šŸš©
chrisachard
Chris Achard

Posted on August 30, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Lists and Keys in React
webdev Lists and Keys in React

September 23, 2022

React Hooks Mini Crash Course
webdev React Hooks Mini Crash Course

August 30, 2019