12. 13/04/2019 reveal.js
localhost:8000/?print-pdf 12/19
REUSE AND COMPOSEREUSE AND COMPOSE
Are hooks kind of like mixins
const MyLocation = () => {
const location = useLocation()
return <p>You are at: {location}</p>
}
const useLocation = () => {
const [location, setLocation] = useState("loading...")
useEffect(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(() =>
setLocation("lat: "+position.coords.latitude+" lng: "+position.coords.longitude)
);
} else {
return "Geolocation is not supported by this browser.";
}
})
return location
}
13. 13/04/2019 reveal.js
localhost:8000/?print-pdf 13/19
HOOKS IN REAL LIFEHOOKS IN REAL LIFE
Our (old) data provider
/* Context */
const DataContext = React.createContext()
/**
* Global user data provider
*
**/
class DataProvider extends React.Component {
constructor(props) {
super(props)
this.state = {
status: 'init',
data: parseData({}),
actions: {fetchData: this.fetchData}
}
}
/**
* Fetch Data only when we are authenticated. This might not happen on initial mounting
/
14. 13/04/2019 reveal.js
localhost:8000/?print-pdf 14/19
HOOKS IN REAL LIFEHOOKS IN REAL LIFE
... now with hooks! ✨
/* Context */
export const DataContext = React.createContext()
/**
* Data Reducer
*/
const reducer = (state, action) => { ... }
/**
* Global user data provider
*
**/
const DataProvider = props => {
/**
* Fetch Data from API endpoint
*/
const fetchData = async () => { ... }
const [state, dispatch] = useReducer(reducer, {
'i i '
15. 13/04/2019 reveal.js
localhost:8000/?print-pdf 15/19
HOOKS IN REAL LIFEHOOKS IN REAL LIFE
Class vs Hooks
async componentDidMount() {
if (this.props.authState === 'signedIn') {
await this.fetchData()
}
}
async componentDidUpdate(prevProps, prevState) {
if (
prevProps.authState !== this.props.authState &&
this.props.authState === 'signedIn'
) {
await this.fetchData()
}
}
useEffect(() => {
if (props.authState === 'signedIn') {
fetchData()
}
}, [props.authState])
16. 13/04/2019 reveal.js
localhost:8000/?print-pdf 16/19
HOOKS UNDER THE HOODHOOKS UNDER THE HOOD
react / packages / react-reconciler / src / ReactFiberHooks.js
// TODO: Not sure if this is the desired semantics, but it's what we
// do for gDSFP. I can't remember why.
if (workInProgressHook.baseUpdate === queue.last) {
workInProgressHook.baseState = newState;
}
...