Intro to react hooks....
Just started learning react and confused between react hooks. This read will clear your all confusion about react hooks.
What are react hooks?
React hooks gives the power to functional components to perform everything that you can do with class components.
Why to use react hooks?
If we can do everything using class based components then why react hooks and eventually functional components. React hooks are introduced for simplicity, cleanliness and to take advantage of component lifecycle methods. React hooks are more readable, much simpler to use, requires less code to write, begineer friendly and most important you can create your own custom hook.
We will take look at 3 basic react hooks:
useState:
useState is a Hook that allows you to have state variables in functional components
Syntax:
const[state,setState]=React.useState(initialState)
When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it.
useEffect:
The Effect Hook lets you perform side effects in function components:
Syntax:
useEffect(callback[, dependencies]);
useEffect accepts 2 parameters.
callback is the callback function containing side-effect logic. useEffect() executes the callback function after React has committed the changes to the screen.
dependencies is an optional array of dependencies. useEffect() executes callback only if the dependencies have changed between renderings
Put your side-effect logic into the callback function, then use the dependencies argument to control when you want the side-effect to run. That’s the sole purpose of useEffect().
We can replicate various lifecycle methods using react useEffect hooks by controlling the depenacy array.
useContext:
React’s useContext hook makes it easy to pass data throughout your app without manually passing props through components that don't use them. syntax:
const value = useContext(ContextValue);
useContext hook is part of react context API. Before useContext we have to create consumer to consume the context. useContext lets us use context without creating consumer.