Upgrade to Pro — share decks privately, control downloads, hide ads and more …

React, let’s Hook Everything

React, let’s Hook Everything

React Hooks, officially released as part of React 16.8+. Hooks make it possible to take a React function component and add state to it or hook lifecycle methods.

Marko Arsić

April 17, 2019
Tweet

More Decks by Marko Arsić

Other Decks in Programming

Transcript

  1. 1

  2. 2

  3. import React, { useState } from 'react' const PassengersTracker =

    () => { const [passengers, setPassengers] = useState(0) const increment = () => { setPassengers(passengers => passengers + 1) } return ( <div> We have {passengers} passengers on board! <br /> <button onClick={increment}>+ New passenger</button> </div> ) }
  4. import React, { useEffect } from 'react' function LifecycleDemo() {

    // It takes a function useEffect(() => { // Called after every render, by default console.log('render!'); // If you want to implement componentWillUnmount, // return a function from useEffect return () => console.log('unmounting...') }) return "I'm a LifecycleDemo component" }
  5. const [value, setValue] = useState('initial'); useEffect(() => { // This

    effect uses the `value` variable, // so it "depends on" `value`. console.log(value); }, [value]) // pass `value` as a dependency
  6. // Create a Context const NumberContext = React.createContext() // It

    returns an object with 2 values: // { Provider, Consumer }
  7. function App() { // Use the Provider to make a

    value available to all children return ( <NumberContext.Provider value={42}> <NumberItem /> </NumberContext.Provider> ) }
  8. import NumberContext from './NumberContext' function NumberItem() { // Use the

    Consumer to grab the value from context // Notice this component didn't get any props return ( <NumberContext.Consumer> {value => <div>The number is {value}.</div>} </NumberContext.Consumer> ) }
  9. useContext // import useContext // (or we can write React.useContext)

    import React, { useContext } from 'react' import NumberContext from './NumberContext' const NumberItem() { const value = useContext(NumberContext) return ( <div>The number is {value}.</div> ) }
  10. 3