Created
October 30, 2018 02:18
-
-
Save MaximeHeckel/8c8604ed0e9ce6e3b76ad9deca84aeb7 to your computer and use it in GitHub Desktop.
Basic React Hooks examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useContext, useEffect, createContext } from "react"; | |
import logo from "./logo.svg"; | |
import "./App.css"; | |
const CounterContext = createContext(0); | |
const Hello = () => { | |
// This avoids render props and the use of Context.Consumer | |
// way easier! | |
const count = useContext(CounterContext); | |
return <div>{count}</div>; | |
}; | |
const App = () => { | |
// Basic state management whith the new React hooks | |
const [count, setCount] = useState(0); | |
// useEffect is basically equivalent to componentDidMount / componentDidUpdate / componentWillUnmount | |
useEffect(() => { | |
document.title = `Hello ${count} times`; | |
}); | |
useEffect(() => console.log("HELLO WORLD")); | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<img src={logo} className="App-logo" alt="logo" /> | |
<h1>React {React.version}</h1> | |
<button onClick={() => setCount(count + 1)}>Click me</button> | |
<CounterContext.Provider value={count}> | |
<Hello /> | |
</CounterContext.Provider> | |
</header> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment