Back to home

React Hook Basics main image

React Hook Basics

Hooks introduces State and Lifecycle Methods to function-based components.

Hooks make it really easy to share logic between components.

Some Basic Hooks

NameFunction
useStateComponent-level state
useEffectUse 'lifecycle methods'
useContextAllow use of context system
useRefAllow func component to use ref system
useReducerAllow func component to store data through a 'reducer'

Before Hooks

// components/App.js import React from 'react'; export default App extends React.Component { state = { counter: 0 } handleClick = () => this.setState({counter: this.state.counter++}) render() { return <div> <button onClick={this.handleClick}>{this.state.counter}</button> </div> } }

After Hooks

// components/App.js import React, { useState, useEffect } from "react"; const App = () => { const [counter, setCounter] = useState(0); const updateCounter = () => setCounter(counter++); useEffect(() => { console.log("Counter updated!"); }, [counter]); return ( <div> <button onClick={updateCounter}>{counter}</button> </div> ); };

Lifecycles with useEffect

useEffect allows us to effectively use a combined version of componentDidMount and componentDidUpdate.

Notes:

  • useEffect argument function cannot be an async func.

import React, { useEffect } from "react"; // second argument controls whether or not the arrow function is called useEffect(() => { console.log("Counter updated!"); }, [counter]);

Code Reuse Example

Believe it or not, what we can actually do is abstract the useEffect outside of the function component.

This is incredibly useful to create reuseable effects.

Personal image

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on Visibuild.

1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.