28
loading...
This website collects cookies to deliver better user experience
npm i use-http
import React, { useEffect, useState } from 'react';
import useFetch from 'use-http'
function UseHTTPExample() {
const [todos, setTodos] = useState([])
const { get, post, response, loading, error } = useFetch('https://jsonplaceholder.typicode.com')
useEffect(() => { initializeTodos() }, []);
async function initializeTodos() {
const initialTodos = await get('/todos')
if (response.ok) setTodos(initialTodos)
}
async function addTodo() {
const newTodo = await post('/todos', { title: 'KPITENG Article Writting' })
if (response.ok) setTodos([newTodo, ...todos])
}
return (
<>
<button onClick={addTodo}>Add Todo</button>
{error && 'Error!'}
{loading && 'Loading...'}
{todos.map(todo => (
<div key={todo.id}>{todo.title}</div>
))}
</>
)
}
export default UseHTTPExample;
npm i react-redux @types/react-redux
import { useSelector, useDispatch } from "react-redux";
import React from "react";
import * as actions from "./actions";
const ReduxHooksExample = () => {
const dispatch = useDispatch();
const counter = useSelector((state) => state.counter);
return (
<div>
<span>{counter.value}</span>
<button onClick={() => dispatch(actions.incrementCounter)}>
Counter +1
</button>
</div>
);
};
npm i use-media
const ResponsiveComponent = () => {
const isWide = useMedia({ minWidth: "1000px" });
return (
<span>
Screen is wide: {isWide ? "It's WideScreen" : "It's NarrowScreen"}
</span>
);
};
npm i react-hook-form
import React from "react";
import { useForm } from "react-hook-form";
function SignUpComponent() {
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data) => {
// logs {firstName:"exampleFirstName", lastName:"exampleLastName"}
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstName" ref={register} />
<input name="lastName" ref={register({ required: true })} />
{errors.lastName && <span>"Last name is a mandatory field."</span>}
<input name="age" ref={register({ required: true })} />
{errors.age && <span>"Please enter number for age."</span>}
<input type="submit" />
</form>
);
}
npm i constate
import React, { useState } from "react";
import constate from "constate";
// custom hook
function useCounter() {
const [count, setCount] = useState(0);
const increment = () => setCount(prevCount => prevCount + 1);
return { count, increment };
}
// hook passed in constate
const [CounterProvider, useCounterContext] = constate(useCounter);
function Button() {
// use the context
const { increment } = useCounterContext();
return <button onClick={increment}>+</button>;
}
function Count() {
// use the context
const { count } = useCounterContext();
return <span>{count}</span>;
}
function App() {
// wrap the component with provider
return (
<CounterProvider>
<Count />
<Button />
</CounterProvider>
);
npm i use-debounce
import React, { useState } from "react";
import { useDebounce } from "use-debounce";
export default function UseDebounceExample() {
const [text, setText] = useState("Hello KPITENG");
const [value] = useDebounce(text, 3);
return (
<div>
<input
defaultValue={"Hello"}
onChange={(e) => {
setText(e.target.value);
}}
/>
<p>Value: {text}</p>
<p>Debounced value: {value}</p>
</div>
);
}
npm i react-router-dom
import { useHistory, useLocation, useRouteMatch } from "react-router-dom";
const RouteExample = () => {
let history = useHistory();
let location = useLocation();
let isMatchingURL = useRouteMatch("/blog/33");
function handleClick() {
history.push("/home");
}
return (
<div>
<span>Current URL: {location.pathname}</span>
{isMatchingURL ? <span>Matching provided URL! </span> : null}
<button type="button" onClick={handleClick}>
Go home
</button>
</div>
);
};
npm i react-use-hover
import useHover from "react-use-hover";
const HoverExample = () => {
const [isHovering, hoverProps] = useHover();
return (
<>
<span {...hoverProps} aria-describedby="overlay">
Hover me
</span>
{isHovering ? <div> Hey, you hover me! </div> : null}
</>
);
};
npm i react-useportal
import React, { useState } from "react";
import usePortal from "react-useportal";
const UsePortalExample = () => {
const { ref, openPortal, closePortal, isOpen, Portal } = usePortal();
return (
<>
<button ref={ref} onClick={() => openPortal()}>
Open Portal
</button>
{isOpen && (
<Portal>
<p>
This Portal handles its own state.{" "}
<button onClick={closePortal}>Close me!</button>, hit ESC or click
outside of me.
</p>
</Portal>
)}
</>
);
};
npm i @rehooks/local-storage
import React, { useState } from "react";
import { writeStorage, useLocalStorage } from '@rehooks/local-storage';
const UseLocalStorageExample() {
let counter = 0;
const [counterValue] = useLocalStorage('counterValue');
return (
<div>
<span>{counterValue}</span>
<button onClick={() => writeStorage('i', ++counter)}>
Click Me
</button>
</div>
);
}