React Flashcards
Learning React hooks and more
useEffect
React comes with a built in hook for “side effects” like
import React, { useEffect, useState } from ‘react’;
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
// This code will run as a side effect.
// You can fetch data, set up event listeners, and more here.
// Example: Fetch data from an API
fetch(‘https://api.example.com/data’)
.then(response => response.json())
.then(data => setData(data));
// Clean up the effect (optional)
return () => {
// This function will be called when the component unmounts or when the dependencies change. // You can use it to clean up any resources or subscriptions. }; }, []);
// Empty dependency array means the effect runs once, similar to componentDidMount
return (
<div>
{/* Render your component with the fetched data */}
{data ? <p>{data.message}</p> : <p>Loading…</p>}
</div>
);
}
useContext
Custom Hooks | LocalStorage Custom hook
Computed Property Name
import React, {useState, useContext} from ‘react’;
import {Link, useHistory} from “react-router-dom”;
import DataContext from ‘../src/helpers/DataContext’;
import Alert from “../common/Alert”;
function LoginForm() {
let history = useHistory();
const [formErrors, setFormErrors] = useState([])
const {login} = useContext(DataContext)
const [formData, setFormData] = useState({
username: “”,
password: “”
});
function handleChange(e) {
const {name, value} = e.target;
setFormData(data => ({…data, [name]:value}))
}
useHistory
- history object is a wrapper over the browser’s history API
- You have access to the history object using the useHistory hook
- The history object has .push(url), which adds URL to the session history.
○ So, unlike <Redirect>, hitting back button will return here
After pushing this new URL, React Router will update the view accordingly.</Redirect>
import {Link, useHistory} from “react-router-dom”;
import DataContext from ‘../helpers/DataContext’;
function LoginForm() {
let history = useHistory()
const {login} = useContext(DataContext)
const [formData, setFormData] = useState({
username: “”,
password: “”
});
async function handleSubmit(e) {
e.preventDefault();
const result = await login(formData);
if(result.sucess) {
history.push(“/”)
}
}
Higher Order Component