Skip to content

Instantly share code, notes, and snippets.

@ljaviertovar
Last active March 8, 2022 00:44
Show Gist options
  • Save ljaviertovar/bb28f850da763978d473371fe331be63 to your computer and use it in GitHub Desktop.
Save ljaviertovar/bb28f850da763978d473371fe331be63 to your computer and use it in GitHub Desktop.
Example of markdown file

Using the State Hook

The introduction page used this example to get familiar with Hooks:

<Code language="javascript"> import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times

<button onClick={() => setCount(count + 1)}> Click me ); } export default Example; </Code>

We’ll start learning about Hooks by comparing this code to an equivalent class example.

Equivalent Class Example

If you used classes in React before, this code should look familiar:

<Code language="javascript"> class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>You clicked {this.state.count} times

<button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me ); } } </Code>

The state starts as { count: 0 }, and we increment state.count when the user clicks a button by calling this.setState(). We’ll use snippets from this class throughout the page.

Note

You might be wondering why we’re using a counter here instead of a more realistic example. This is to help us focus on the API while we’re still making our first steps with Hooks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment