intro to hooks

hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

 

but first...

Destructuring assignment

 

const arr = [10,12,13,14]

const [first, second] = arr

const first = arr[0]
const second = arr[1]

console.log(first) // will log out 10

console.log(second) // will log out 12

// Bonus: 

const [firstValue, secondValue, ...theRest] = arr

const firstValue = arr[0]
const secondValue = arr[1]
const theRest = arr.slice(2)

let's talk about functional components

class HelloMessage extends React.Component {
  render() {
    return (
      <div>
        Hello {this.props.name}
      </div>
    );
  }
}

What we are used to...

import React from 'react'

const HelloWorld = (props) => {
  return (
      <div>
        Hello {props.name}
      </div>
    );
}

but we really don't "need" classes

Why use functional components: 

 

  • overall simpler code, things are "just functions"
  • easier to deal with scope and state
  • classes are hard for everyone
  • can't use state*

* until now!

hooks!

hooks give us the ability to use state without having to use a Class component.s

with out hooks

class Counter() extends Component {
  state = {
    count: 0
  }
  setCount = (newCount) => {
      this.setState({
        count:newCount
      })
  }
  render() {
    return (
        <>
          Count: {this.state.count}
          <button 
            onClick={() => setCount(0)}>
              Reset
          </button>
          <button 
            onClick={() => setCount(this.state.count + 1)}>
              Add 1
          </button>
          <button 
            onClick={() => setCount(this.state.count - 1)}>
            Subtract 1
          </button>
        </>
      );

  }
}

hooks

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <>
      the current count is : {count}
      <button 
        onClick={() => setCount(0)}>
          Reset
      </button>
      <button 
        onClick={() => setCount(prevCount => prevCount + 1)}>
          Add 1
      </button>
      <button 
        onClick={() => setCount(prevCount => prevCount - 1)}>
        Subtract 1
      </button>
    </>
  );
}

let's refactor some old code. 

Hooks; Functional components; destructoring

By Mark Dewey

Hooks; Functional components; destructoring

  • 230