sandra-larsson
Educator Fullstack Developer Javascript at Chas Academy
“Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.” — React Docs
“useState is a Hook […] We call it inside a function component to add some local state to it. React will preserve this state between re-renders.” — React Docs
“useState
returns a pair: the current state value and a function that lets you update it.” — React Docs
const [state, setState] = React.useState(initialValue)
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</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}
“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..” — React Docs
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect(callback[, dependencies]);
useEffect() tar in två argument
om dependencies utelämnas?
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Runs after EVERY rendering
});
}
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Runs ONCE after initial rendering
}, []);
}
import React, {useState, useEffect} from 'react';
import './App.css';
function App() {
let [dogImage, setDogImage] = useState(null)
useEffect(() => {
fetch("https://dog.ceo/api/breeds/image/random")
.then(response => response.json())
.then(data => setDogImage(data.message))
},[])
return (
<div className="App">
{dogImage && <img src={dogImage}></img>}
</div>
);
}
export default App;
Exempel: fetch from API
By sandra-larsson