Skip to content

Instantly share code, notes, and snippets.

@KRostyslav
Last active September 12, 2022 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KRostyslav/08961e7de1a1b1042ccabfa4299356b4 to your computer and use it in GitHub Desktop.
Save KRostyslav/08961e7de1a1b1042ccabfa4299356b4 to your computer and use it in GitHub Desktop.
React Hooks

React Hooks

from React v.16.8

  • useState
  • useReducer
  • useEffect
  • useLayoutEffect
  • useContext
  • useMemo
  • useCallback
  • useRef
  • useImperativeHandle
  • useDebugValue
  • useDeferredValue
  • useTransition
  • useId
useCallback(fn, [deps]);
import { useContext } from ‘react’;

const { Provider, Consumer } = React.createContext();
import {useEffect} from ‘react’;

// 1.
useEffect(() => {
    console.log(“Hello”);
});

// 2.
useEffect(() => {
    console.log(“Hello”);
}, []);

// 3.
useEffect(() => {
    console.log(“Hello”);
}, [dep1, dep2]);

// 4.
useEffect(() => {
    console.log(“Hello”);

    return ()=>{
        console.log('Good bye)
    }
}, []);
useMemo(() => {
	fn, [deps];
});
import { useReducer } from ‘react’;

const initialState = { count: 0 }

function reducer(state, action) {
    switch (action.type) {
        case 'add':
            return { count: state.count + 1 }
        case 'delete':
            return { count: state.count  1 }
        case 'update':
            return {count: state.count = 0}
        default:
            return { count: state.count }
    }

}

const Component = () => {

const [state, dispatch] = useReducer(reducer, initialState)

return (
    <div>
        <button onClick={() => dispatch({ type: 'add' })}>Add</button>
        <button onClick={() => dispatch({ type: 'delete'})}>Delete</button>
        <button onClick={() => dispatch({ type: 'update'})}>Update</button>
    </div>
);

};

export default Component;

useState hook - managing component state

JS

//
import { useState } from “react”;

const [ state, setState ] = useState();

// initial value
const [ state, setState ] = useState( initialValue );

// passing a function  as the initial value
const initFunc = ( newValue ) => {
    ...
    return updatedValue
}

const [ state, setState ] = useState( initFunc );



setState( newValue );
setState( prevValue => prevValue + newValue );

Batching of state updates

const update = () => {
	setValueA(1);
	// Force this state update to be synchronous.
	flushSync(() => {
		setValueB(2);
	});
	setValueC(3);
	setValueD(4);
	setValueE(5);
};

TS

const [state, setState] = useState<T>();

const [state, setState] = useState<T>(initialValue);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment