React hooks in 1 min
I will be explaining majorly used react hooks in brief in this blog post. So without any delay, let’s get started:
UseState:
const [name, setName] = useState("");
Returns a stateful value and a function to update that value.
Contains initial value as a parameter to it.
Updating state -> setName(“Dk”)
UseEffect:
useEffect(
() => {
const data = fetch(...);
return () => {
cancelRequest();
};
},
[dependency],
);
Provide lifecycle methods in react and used for controlling side effects like fetching data, subscribing, listening to state changes, updating DOM etc.
Takes a function as parameter and runs on every render.
Dependency array is used to tell when should it re run. Leave it empty if you want to run something once.
returns a function that runs on unmounting of component generally used to cancel side effects.
useContext:
const value = useContext(context);
Used to escape from prop drilling.
Accepts a context object created from React.createContext
returns value of the context passed from the parent.
useReducer:
const [state, dispatch] = useReducer(reducer, initialArg);
used to manage state more effectively in larger projects or where code becomes large.
Accepts a reducer of type (state, action) => newState
, and returns the current state paired with a dispatch
method.
useRef:
const ref = useRef(null)
Basically used to hold a reference of DOM element.
parameter -> initial value for reference.
initially ref.current is null and is set like this.
<span ref={ref}></span>
useMemo:
const memoizedValue = useMemo(function);
returns a memoized value.
parameter -> function that can also have dependency like useEffect.
memoized i.e cached the value passed to it … can be any complex function or a complete function.
fetched the value from cache until variable specified in dependency array changes.
useLayoutEffect:
useLayoutEffect(() => {
console.log(count)
}, [count])
have same signature of useEffect.
runs synchronously after all DOM mutations.
used for DOM changes.