REACT HOOKS

recycle your application logic

by Gian Marco Toso   -   @gianmarcotoso

self employed / polarityb.it

Hooks

Hooks are functions that can be called within a function component;

 

They allow to manage operations such as side effects, local state management, memoization and context access

How Does it work?

import React, { useState, useEffect, useMemo } from 'react'

export function MyAwesomeComponent({ title }) {
    const [count, setCount] = useState(0)
    
    useEffect(() => {
    	console.log('The counter has changed!')
    }, [count])
    
    useEffect(() => {
    	console.log('The title has changed!')
    }, [title])
    
    const expensiveValue = useMemo(() => {
    	for(let i = 0; i < 10e5; i++);
        return 42
    })

    return (
        <div>
            <h1>{title}</h1>
            <div>
            	<span>I have counted to {count}</span>
                <button onClick={() => setCount(c => c + 1)}>One more!</button>
            </div>
            <div>This is an expensive value: {expensive}</div>
        </div>
    )
}

Custom Hooks!

React provides a certain number of default hooks

These can be composed, along with custom logic, to create custom, reusable hooks that encapsulate any kind of application logic

Custom Hooks!

import React, { useState, useEffect } from 'react'

export function useRemoteData() {
    const [data, setData] = useState(null)
    const [error, setError] = useState(null)
    const [loading, setLoading] = useState(false)
    
    useEffect(() => {
    	setLoading(true)
        
    	fetch('https://my.api.com/data')
        	.then(res => {
            	return res.json() 
            })
            .then(json => {
            	setData(json)
            })
            .catch(error => {
            	setError(error)
            })
            .finally(() => {
            	setLoading(false)
            })
    }, [])
    
    return { data, error, loading }
}

Open discussion

  • Can hooks be used for ... ?
  • Are hooks synchronous or asynchronous?
Made with Slides.com