Back to home

Some Basic HooksBefore HooksAfter HooksLifecycles with useEffectCode Reuse Example
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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // 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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // 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.
1 2 3 4 5 6 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.

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 workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.