Skip to content

Instantly share code, notes, and snippets.

@RobMacKay
Created September 17, 2020 07:33
Show Gist options
  • Save RobMacKay/c6f13cf664d45dc4ad0293d1368417a4 to your computer and use it in GitHub Desktop.
Save RobMacKay/c6f13cf664d45dc4ad0293d1368417a4 to your computer and use it in GitHub Desktop.
Example Stateful Functional Component React.
import React, {useEffect, useState} from 'react'
export default function Example(props) {
// you don't have to call these state and setState.
const [state, setState] = useState([state])
// Think of this as ComponentDidMount
useEffect(() => {
// You can put all javascript in here like "componentDidMount"
// You can check and update state here too - simple fetch example:
let url = "https://myrest.com/api/endpoint"
fetch(url)
.then(res => res.json())
.then(res => setState(res))
.catch(error => console.log(error))
}, [state]) // this is to "check for changes" - otherwise useEffect will loop and you will be confused.
return (
<div>
{state.title}
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment