37
loading...
This website collects cookies to deliver better user experience
api: https://v2.jokeapi.dev/joke/Any
const [state,setState] = useState();
// state will have the initial state in this case undefined
// setState is the function that we can use to update the state
setState("words")
// you would use it as such,
//the parameter takes in the value you want to update the state with
import {useState} from 'react';
import './App.css';
function App() {
//we created a state joke that is intialized with a string value for now
const [joke,setJoke] = useState("There are only 10 kinds of people in this world: those who know binary and those who don't.")
return (
<div className="App">
<header className="App-header">
<h3>{joke}</h3>
</header>
</div>
);
}
export default App;
useEffect()
method to replace componentDidMount
, componentDidUpdate
, and componentWillUnmount
. useEffect()
will run after every component render.useEffect Accepts a function that contains imperative, possibly effectful code.
Mutations, subscriptions, timers, logging, and other side effects are not allowed
inside the main body of a function component (referred to as React’s render phase).
Doing so will lead to confusing bugs and inconsistencies in the UI.
Instead, use useEffect. The function passed to useEffect will run after the render
is committed to the screen. Think of effects as an escape hatch from React’s purely
functional world into the imperative world.
By default, effects run after every completed render,
but you can choose to fire them only when certain values have changed.
//Example
useEffect(()=>{
fetchData() // making a network request
//eveythig inside this function will be called on every render
//fetchData() will be called everytime the component re-renders
})
useEffect
takes a dependencies array as a second parameter, useEffect()
method and the setJoke()
method that we got from useState()
import {useState, useEffect} from 'react';
import './App.css';
function App() {
const [joke,setJoke] = useState("")
useEffect(()=>{
getRandomJoke();
})
//fetching the data and setting and updating state
const getRandomJoke = async () => {
const response = await fetch("https://v2.jokeapi.dev/joke/Any?type=single");
const result = await response.json();
if(!result.error){
setJoke(result.joke);
}
}
return (
<div className="App">
<header className="App-header">
<h3>{joke}</h3>
</header>
</div>
);
}
export default App;
useEffect()
method is running every single time the joke
state is changing, this makes it run useEffect(()=>{
getRandomJoke();
},[]) //passed an empty array []