React Hooks Part 1
Viktor Nawrath
1
Oct/2022
React Component
2
Oct/2022
import { CounterDisplay } from "./components/CounterDisplay"; export default function App(props) { const [counter, setCounter] = useState(props.initialCount); return ( <div> <CounterDisplay count={counter} /> <button onClick={() => setCounter(counter + 1)}>Increment</button> </div> ); } |
export function CounterDisplay(props) { const { count } = props; return <p>{count}</p>; } |
Functional component lifecycle
3
Oct/2022
export default function App(props) { const [counter, setCounter] = useState(0); useEffect(() => { const interval = setInterval( () => setCounter((c) => c + 1), 1000 ); return () => clearInterval(interval); }, []); return ( <div> <CounterDisplay count={counter} /> </div> ); } |
React hooks
4
Oct/2022
BETA React docs
5
Oct/2022
useState hook
6
Oct/2022
useState hook
7
Oct/2022
// You can set the initial value as a first argument const [name, setName] = useState("Jane"); // You can provide the initial value as a function, // the function will only get called on first render const [balance, setBalance] = useState(() => expensiveFunction()); // You can then set the value using the returned setter // Either by providing the new value setName("Marie") // Or using a function, that receives the previous state as argument setBalance((previousBalance) => previousBalance + 420) |
useReducer hook
8
Oct/2022
const initialState = {count: 0}; function reducer(state, action) { switch (action.type) { case 'increment': return {count: state.count + 1}; case 'decrement': return {count: state.count - 1}; default: throw new Error(); } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> Count: {state.count} <button onClick={() => dispatch({type: 'decrement'})}>-</button> <button onClick={() => dispatch({type: 'increment'})}>+</button> </> ); } |
text
9
Sep/2021
Thank you for your attention
Petr Večeřa
+420 775 350 603
petr.vecera@vsb.cz
www.vsb.cz