React — Hooks

Lokesh
2 min readJan 18, 2021

First, let us understand why do we need hooks?

When we create function components instead of class components, we miss some of the main functions provided by react i.e. life cycle components like componentDidMount, etc. So we to overcome this limitation we have hooks. Hooks allow us to hook into the react state and also life cycle features from function components.

There are many react hooks, let us discuss some of them

  • useSelector()

This hook can be used when the application wants to read any data from the redux store. For example, we have a redux store and we want to get the user details from that then to get that from the store we can write the code as,

const userDetails = useSelector(state => state.Login.userDetails);
  • useDispatch()

It is used when we want to dispatch any action to update the store from our component. Example — Say we want to dispatch an action it may be an API call or any other actions then we can write the code as,

const dispatch = Dispatch();
dispatch(action_name());
  • useState()

The use state is used to preserve the value between the function calls, useState() is similar to this.state which we use in class components. Normally, variables “disappear” when the function exits but state variables are preserved by React. Example,

const[value, setValue] = useState(false);
now we can set the value by,
setValue(true);

Here in the array we have 2 elements “value”,”setValue”, setValue is used to set the value. we have initialized the state value to false, but we can change the value by setValue(true).

  • useEffect()

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. Example,

useEffect(() => {
const subscription = props.source.subscribe();
return () => {
// Clean up the subscription
subscription.unsubscribe();
};
},
[array similar to component did update]
);

--

--