Hooks introduces State and Lifecycle Methods to function-based components.
Hooks make it really easy to share logic between components.
| Name | Function |
|---|---|
| useState | Component-level state |
| useEffect | Use 'lifecycle methods' |
| useContext | Allow use of context system |
| useRef | Allow func component to use ref system |
| useReducer | Allow func component to store data through a 'reducer' |
// 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> } }
// 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> }
useEffect allows us to effectively use a combined version of componentDidMount and componentDidUpdate.
Notes:
import React, {useEffect} from 'react'; // second argument controls whether or not the arrow function is called useEffect(() => { console.log('Counter updated!'); }, [counter]);
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.