What are react hooks and how to use them

Photo by CHUTTERSNAP on Unsplash

What are React hooks

Hooks are functions that hook into react state and lifecycle features from the function component. It does not work in class components.

https://reactjs.org/docs/hooks-reference.html

Why should we write hooks instead of class-based components

useState

The ‘useState” hook returns a state value equal to the initial state argument passed in, and a function to update the state value.

const [state, setState] = useState(initialState);
setState(prevState => preState - 1);setState(someValue);

useEffect

useEffect(callback[, dependencies]);
useEffect hook’s clean up process

Best practice

In general, putting the side-effect logics in the callback function, and using the dependencies array to control when to fire the callback function.

useEffect(() => { console.log(“some logic”); }, []);
function App() { useEffect(() => {//Execute logic}, [props, state]);
useEffect(() => {// Side-effect logic…return function cleanup() {// Side-effect cleanup…};}, [dependencies]);

useContext

Prerequisites

Context API allows you to pass value between components without having to explicitly pass a prop through every level of three.

Context API in detail

const MyContext = React.createContext(defaultValue);
<MyContext.Provider value={/* some value */}>
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
Standard Context API usage

How useContext works

Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.

useContext hooks usage

useReducer(To be continue…)

useCallback

useMemo

useRef

The useRef hook helps us accessing a DOM element without causing a re-rendering of the component. The useRef hook returns a mutable object with a property “current”, whose value initialized to the passed argument. The returned ref object can be placed in the react component’s ref attribute.

useImperativeHandle

useLayoutEffect

useDebugValue

Rules of hooks

Only call Hooks at the top level.

Further reading ‘

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
WangYeUX

WangYeUX

A front-end developer who likes designing stuffs. Technical blog rookie. Loving sharing.