What are react hooks and how to use them

React hooks hook out great features of react for your to use in functional components.

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

The “setState” function can take a function as an argument, or it can also take a value to update the state.

setState(prevState => preState - 1);setState(someValue);

No matter what, the setState function will update the target state and trigger a rerender.

useEffect

useEffect(callback[, dependencies]);

The callback” is a callback function containing side-effect logic. It will be fired right after the completed render of this component.

The “dependencies” is an optional array of dependencies. The useEffect will execute only when the dependencies change between renderings.

Sometimes side-effects need cleanup. To do this, the callback function can return a cleanup function. There are two benefits of the clean-up process: First, the clean-up function runs before the component is removed from the UI to prevent memory leaks. Second, if the component renders multiple times, the previous side-effect is cleaned up before executing the next one.

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.

Executing useEffect Only once right after the first render. It is like putting logic in the componentDidMount() lifecycle function.

useEffect(() => { console.log(“some logic”); }, []);

Executing useEffect after props or state changes. It is a replacement of componentDIdUpdate() of class-based component.

function App() { useEffect(() => {//Execute logic}, [props, state]);

Executing clean-up process before unmounting a component.

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

React.createContext() returns a context object that can be used across all levels of components without passing through props. The optional argument can be used as the default value when Context.Provider does not provide any value.

<MyContext.Provider value={/* some value */}>

MyContext.Provider lets wrapped components subscribe to the context. As a result, any components which subscribe to the context will re-render when the context value changes.

The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. If it does provide the value prop, the default value provided in React.createContext will be used.

One Provider component can link to many consumer components. However, when there are multiple provider components exist, only the nearest provider will take effect.

<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>

A component can subscribe to a context by wrapping itself in the context’s consumer component. The component requires a function as a child and returns a React node based on the context value.

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.

When the nearest <MyContext.Provider> above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider.

useContext hooks usage

The remaining ones are not very commonly used, so there is only some brief introduction. The specific details can refer to the official website documents in actual use.

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.

Only call Hooks from React functions

Further reading ‘

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