Skip to content
Swizec Teller - a geek with a hatswizec.com

React hooks in a nut shell ๐Ÿฅ

There's no hook emojiโ€ฆ croissants look like hooks, right?

Mmmmโ€ฆ croissants with some sort of nut cream filling. Get it, hooks in a nutshell? Ha

Maybe I'm hungry ๐Ÿค”

So anyway, React hooks took the React world by storm this weekend. They're not even out yet! And yet here we are.

JavaScript lyfe: New thing comes out, rocks the world, everyone says it's the next best thing since jQuery and will definitely make all your code better and all your knowledge obsolete. Time to learn stuff!

Untrue.

React hooks are neat. They look useful. They don't deprecate anything. Please don't rewrite your apps in hooks. Yet.

I watched Ryan's talk 90% cleaner with hooks last night, Dan's and Sophie's talk announcing hooks this morning, read all the docs, and watched Twitter like a disinterested hawk all weekend.

Hours of research condensed into the next 200 words because I love you. โค๏ธ

Here's what you need to know about hooks right now ๐Ÿ‘‡

You can try them out.

  1. create-react-app look-ma-no-classes
  2. Open package.json, change react and react-dom to next
  3. yarn install

Try out hooks

Hooks exist to rid your codebase of classes. Because classes are confusing to both people and compilers.

Where you used to class, you can now hook. In your functional components.

Built-in hooks cover the most common uses cases. You can build your own for everything else.

useState

The useState hook replaces pairs of state getters and setters.

class myComponent extends React.Component {
state = {
value: 'default'
}
handleChange = (e) => this.setState({
value: e.target.value
})
render() {
const { value } = this.state;
return <input value={value} onchange={handleChange}>
}
}

๐Ÿ‘‡

const myComponent = () => {
const [value, setValue] = useState('default');
const handleChange = (e) => setValue(e.target.value)
return <input value={value} onchange={handleChange}>
}

Less code to write and understand.

In a class component, you:

  • set a default value
  • create an onChange callback that fires setState
  • read value from state before rendering etc.

Without modern fat arrow syntax, you might run into trouble with binds.

The hook approach moves that boilerplate to React's plate. You call useState. It takes a default value and returns a getter and a setter.

You call that setter in your change handler.

Behind the scenes, React subscribed your component to that change. Your component re-renders.

useEffect

useEffect replaces the componentDidMount, componentDidUpdate, shouldComponentUpdate, componentWillUnmount quadfecta. It's like a trifecta, but four.

Say you want a side-effect when your component updates, like make an API call. Gotta run it on mount and update. Want to subscribe to a DOM event? Gotta unsubscribe on unmount.

Wanna do all this only when certain props change? Gotta check for that.

Class:

class myComp extends Component {
state = {
value: 'default'
}
handleChange = (e) => this.setState({
value: e.target.value
})
saveValue = () => fetch('/my/endpoint', {
method: 'POST'
body: this.state.value
})
componentDidMount() {
this.saveValue();
}
componentDidUpdate(prevProps, prevState) {
if (prevState.value !== this.state.value) {
this.saveValue()
}
}
render() {
const { value } = this.state;
return <input value={value} onchange={handleChange}>
}
}

๐Ÿ‘‡

const myComponent = () => {
const [value, setValue] = useState('default');
const handleChange = (e) => setValue(e.target.value)
const saveValue = () => fetch('/my/endpoint', {
method: 'POST'
body: this.state.value
})
useEffect(saveValue, [value]);
return <input value={value} onchange={handleChange}>
}

So much less code!

useEffect runs your function on componentDidMount and componentDidUpdate. And that second argument, the [value] part, tells it to run only when that value changes.

No need to double check with a conditional. If your effect updates the component itself through a state setter, the second argument acts as a shouldComponentUpdate of sorts.

When you return a method from useEffect, it acts as a componentWillUnmount. Listening to, say, your mouse position looks like this:

const [mouseX, setMouseX] = useState();
const handleMouse = (e) => setMouseX(e.screenX);
useEffect(() => {
window.addEventListener("mousemove", handleMouse);
return () => window.removeEventListener(handleMouse);
});

Neat ๐Ÿ‘Œ

Waiting for the day we can use this to do naughty DOM stuff in functional components. Limiting factor right now is that we can't have refs I think.

useContext

useContext cleans up your render prop callbacky hell.

<somecontext>
{state => ...}
</somecontext>

๐Ÿ‘‡

const state = useContext(SomeContext);

Context becomes just a value in your function. React auto subscribes you to all updates.

useReducer

useReducer is like React got Redux built in now. Whoa.

You don't really have to know this one. But it comes by default and it's kinda neat. Although I think using it for realz will lead to your components becoming way too big and bloated.

You should watch Ryan's talk to learn more about this one. Too long to explain in a nutshell ๐Ÿฅ post.

So?

Will hooks change the way you write React forever? We'll see. The internet is excited.

You can write your own hooks. Repositories of hooks are popping up like crazy. I'm sure your internet will be full of them for the next while.

Most importantly ๐Ÿ‘‡

You can write your own hooks and re-use functionality between components. It's just a function.

Dan and Sophie say this is the future of React. All functional. No classes.
But right now, it's just a Request For Comments. So comment away.

Did you enjoy this article?

Published on October 29th, 2018 in Front End, Technical

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works ๐Ÿ‘‡

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet ๐Ÿ“–right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet ๐Ÿ“–

Then get thoughtful letters ๐Ÿ’Œ on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. ๐Ÿ‘Œ"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. โœŒ๏ธ

Have a burning question that you think I can answer?ย I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own? ย Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first ๐Ÿ’ฐ on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax?ย Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you areย โค๏ธ

Created bySwizecwith โค๏ธswizec.com