React Flashcards

Learning React hooks and more

1
Q

useEffect

A

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>
);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

useContext

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Custom Hooks | LocalStorage Custom hook

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Computed Property Name

A

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}))
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

useHistory

A
  • 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(“/”)
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Higher Order Component

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly