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

useState(props.title)

 useState(props.title)

Sibiu Web Meetup #11

Speaker: Lucian Petri

Sibiu Web Meetup

October 15, 2020
Tweet

More Decks by Sibiu Web Meetup

Other Decks in Programming

Transcript

  1. VS Class React • Lifecycle methods • constructor() • This.

    • State & setState() Functional React • React Hooks <3 • ES6 components ( ) => {} • RIP This.
  2. A Simple Clock App Class based Component class ClockApp extends

    React.Component { constructor (props) { super(props); this.state = { date: new Date() }; } componentDidMount () { this.time = setInterval (() => { this.changeTime (); } , 1000); } componentWillUnmount () { clearInterval (this.time); } changeTime () { this.setState ({ date: new Date() }); } render() { return ( < div className ="clock"> < h1>Hello! This is a class component clock.</ h1> < h2>It is {this.state.date.toLocaleTimeString ()}</h2> </ div> ); } } Functional Component const ClockApp = () => { const [time, changeTime] = useState (new Date()); useEffect (() => { const tick = setInterval (() => { changeTime (new Date()); } , 1000); return () => clearInterval (tick); }); return ( < div className ="clock"> < h1>Hello! This is a function component clock.</ h1> < h2>It is {time.toLocaleTimeString ()}.</h2> </ div> ); }
  3. Why JSX? React embraces the fact that rendering logic is

    inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display. Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.
  4. const element = <h1>Hello, world!</h1>; const element = { type:

    "h1", props: { children: "Hello, World!" } }
  5. What is the Virtual DOM? The virtual DOM (VDOM) is

    a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation. This approach enables the declarative API of React: You tell React what state you want the UI to be in, and it makes sure the DOM matches that state. This abstracts out the attribute manipulation, event handling, and manual DOM updating that you would otherwise have to use to build your app. Since “virtual DOM” is more of a pattern than a specific technology, people sometimes say it to mean different things. In React world, the term “virtual DOM” is usually associated with React elements since they are the objects representing the user interface. React, however, also uses internal objects called “fibers” to hold additional information about the component tree. They may also be considered a part of “virtual DOM” implementation in React
  6. Web application Document Object Model < div className ="clock"> <

    h1>Hello! This is a function component clock.</ h1> < h2>It is TIME.</h2> </ div> Change <div className ="clock"> <h1>Hello! This is a function component clock.</ h1> <h2>It is NEW TIME .</h2> </div> <div className ="clock"> <h1>Hello! This is a function component clock.</ h1> <h2>It is TIME.</h2> </div> reconciliation <div className ="clock"> <h1>Hello! This is a function component clock.</ h1> <h2>It is NEW TIME .</h2> </div> Re-Render Only Changes
  7. Functional Component const ClockApp = () => { const [time,

    changeTime] = useState(new Date()); useEffect(() => { const tick = setInterval(() => { changeTime(new Date()); }, 1000); return () => clearInterval(tick); }); return ( <div className="clock"> <h1>Hello! This is a function component clock.</h1> <h2>It is {time.toLocaleTimeString()}.</h2> </div> ); }
  8. const [time, changeTime] = useState(new Date()); Easy Access of the

    components state Function to change the value when needed
  9. useState useEffect useContext useMemo useCallback useRef Magic of Hooks Land

    . . . useReducer useImpertiveHandle useLayoutEffect useDebugValue
  10. Initial Value from Local Storage ? Get value from a

    Database ? Real-time data from a websocket ? Easier usage with Arrays ? Async values ? Debounce value ? Quickly Access previous value?
  11. const useAsync = (asyncFunction, immediate = true) => { const

    [status, setStatus] = useState ('idle'); const [value, setValue] = useState (null); const [error, setError] = useState (null); // The execute function wraps asyncFunction and // handles setting state for pending, value, and error. // useCallback ensures the below useEffect is not called // on every render, but only if asyncFunction changes. const execute = useCallback (() => { setStatus ('pending' ); setValue (null); setError (null); return asyncFunction () . then(response => { setValue (response); setStatus ('success' ); }) . catch(error => { setError (error); setStatus ('error' ); }); }, [asyncFunction]); // Call execute if we want to fire it right away. // Otherwise execute can be called later, such as // in an onClick handler. useEffect (() => { if (immediate) { execute (); } }, [execute, immediate]); return { execute, status, value, error }; }; Using async Values
  12. function App() { const { execute, status, value, error }

    = useAsync(myFunction, false); return ( <div> {status === 'idle' && <div>Start your journey by clicking a button</div>} {status === 'success' && <div>{value}</div>} {status === 'error' && <div>{error}</div>} <button onClick={execute} disabled={status === 'pending'}> {status !== 'pending' ? 'Click me' : 'Loading...'} </button> </div> ); } // An async function for testing our hook. // Will be successful 50% of the time. const myFunction = () => { return new Promise((resolve, reject) => { setTimeout(() => { const rnd = Math.random() * 10; rnd <= 5 ? resolve('Submitted successfully ') : reject('Oh no there was an error '); }, 2000); }); };
  13. Debounce Value function useDebounce(value, delay) { const [debouncedValue , setDebouncedValue]

    = useState(value); useEffect( () => { const handler = setTimeout(() => { setDebouncedValue (value); } , delay); return () => { clearTimeout (handler); }; },[value, delay]); return debouncedValue; }
  14. function App() { const [searchTerm , setSearchTerm] = useState ("");

    const [results , setResults] = useState ([]); const [isSearching , setIsSearching] = useState (false); const debouncedSearchTerm = useDebounce (searchTerm , 500); useEffect ( () => { if (debouncedSearchTerm) { setIsSearching (true); searchCharacters (debouncedSearchTerm) .then((results) => { setIsSearching (false); setResults (results); }); } else { setResults ([]); } } , [debouncedSearchTerm] // Only call effect if debounced search term changes ); return ( < div> < input placeholder ="Search Marvel Comics" onChange ={(e) => setSearchTerm (e.target.value)} /> {isSearching && <div>Searching ...</ div>} {results.map((result) => ( < div key={result.id}> < h4>{result.title}</h4> < img src={`${result.thumbnail .path}/portrait_incredible. ${result.thumbnail .extension }`} /> </ div> )) } </ div> ); }