useRef and UseReducer Hooks

Zainab Omar
1 min readAug 13, 2021

1. useRef Hook

useRef is a built-in React hook that accepts one argument as the initial value and returns a reference . useRef is useful when creating forms. useRef allows you to directly create a reference to the DOM element in the functional component. It is like a “box” that can hold a mutable value in its .current property. useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

function UseRefHook() {
const input = useRef(null);
const onButtonClick = () => {
input.current.focus();
};
return (
<>
<input ref={input} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}

2. useReducer Hook

useReducer is alternative to useState; it accepts state and action and returns the current state paired with a dispatch method.useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

const initialState = {count: 0};

function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}

Resources https://reactjs.org/docs/hooks-reference.html#usecontext

--

--