Skip to content

Instantly share code, notes, and snippets.

@MaximeHeckel
Created October 30, 2018 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaximeHeckel/8c8604ed0e9ce6e3b76ad9deca84aeb7 to your computer and use it in GitHub Desktop.
Save MaximeHeckel/8c8604ed0e9ce6e3b76ad9deca84aeb7 to your computer and use it in GitHub Desktop.
Basic React Hooks examples
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