Skip to content

Instantly share code, notes, and snippets.

@d0rsha
Last active March 20, 2023 16:41
Show Gist options
  • Save d0rsha/4059ddb9743605d9fa410fb63b8921b8 to your computer and use it in GitHub Desktop.
Save d0rsha/4059ddb9743605d9fa410fb63b8921b8 to your computer and use it in GitHub Desktop.
[React hooks] React hooks #react

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

State hook

import React, { useState } from 'react';

A Hook is a special function that lets you “hook into” React features. In a function component, we have no this, so we can’t assign or read this.state. Instead, we call the useState Hook directly inside our component:

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

Effect Hook

You’ve likely performed data fetching, subscriptions, or manually changing the DOM from React components before. We call these operations “side effects” (or “effects” for short) because they can affect other components and can’t be done during rendering.

When you call useEffect, you’re telling React to run your “effect” function after flushing changes to the DOM. Effects are declared inside the component so they have access to its props and state. By default, React runs the effects after every render — including the first render.

componentDidMount() { ... }

useEffect(() => { 
	... 
}, [])

componentDidUpdate() { ... }

const [clicks, setClicks] = useState(0)
useEffect(() => {
	...
}), [clicks])

<button onClick={(e) => setClicks(clicks + 1)} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment