Skip to content

Instantly share code, notes, and snippets.

const UserContext = React.createContext();
const App = () => {
const username = "John Doe";
const otherData = {};
return (
<UserContext.Provider value={{ username, otherData }}>
<Header />
</UserContext.Provider>
);
// With empty array
useEffect(() => {
console.log('I will run only once');
}, []);
// Without the second parameter
useEffect(() => {
console.log('I will run after every render');
});
// With the second parameter
useEffect(() => {
console.log('I will run only when valueA changes');
}, [valueA]);
import React from 'react';
import useGlobalHook from 'use-global-hook';
const initialState = {
counter: 0,
};
const actions = {
addToCounter: (store, amount) => {
const newCounterValue = store.state.counter + amount;
function setState(newState) {
this.state = { ...this.state, ...newState };
this.listeners.forEach((listener) => {
listener(this.state);
});
}
function useCustom(React) {
const newListener = React.useState()[1];
React.useEffect(() => {
import React from 'react';
import useGlobalHook from './useGlobalHook';
const initialState = { counter: 0 };
const useGlobal = useGlobalHook(React, initialState);
export default useGlobal;
function setState(newState) {
this.state = { ...this.state, ...newState };
this.listeners.forEach((listener) => {
listener(this.state);
});
}
function useCustom(React) {
const newListener = React.useState()[1];
React.useEffect(() => {
const useCustom = () => {
const newListener = useState()[1];
useEffect(() => {
// Called just after component mount
listeners.push(newListener);
return () => {
// Called just before the component unmount
listeners = listeners.filter(listener => listener !== newListener);
};
}, []);
import React from 'react';
import useCustom from './customHook';
const Counter = () => {
const [globalState, setGlobalState] = useCustom();
const add1Global = () => {
const newCounterValue = globalState.counter + 1;
setGlobalState({ counter: newCounterValue });
};
import { useState, useEffect } from 'react';
let listeners = [];
let state = { counter: 0 };
const setState = (newState) => {
state = { ...state, ...newState };
listeners.forEach((listener) => {
listener(state);
});