Introducing React Hooks - Learn useEffect, useState and useMemo

We are going to understand How to use React Hooks here, specifically about useEffect, useState and useMemo. Hooks are the features introduced by React to use state and other functionality (such as componentwillmount, componentwillreceiveprops) in Function based Component. I have made youtube video on this topic as well, you can watch (in English or in Hindi) video on the topic.

You can use state, componentwillmount, componentwillreceiveprops and other methods only in Class based Component.

useState

This is use to manage states on functional components. The method expects a state variable (which can be integer, string, boolean, array or an object) and a setter function (which is use to set the new values in the state variable). 

const [users, setUsers] = useState([]);

 useEffect

This method will get executed on first rendering of your component. Plus, it will get executed based dependencies (when there is change in values of any of the dependencies).

  useEffect(() => {
    getUser();
  }, []);

useMemo

This method is used to memoize any variable's value based on dependencies. It is like useEffect in way to get executed based on dependencies. It stores value and assign to a variable.

const title = useMemo(() => {
    return users.length > 10 ? 'More than 10 users' : users.length === 0 ? 'No users available' : '10 Users';
  }, [users.length]);

Here is the code:

Here is the Youtube Video:



Comments

Popular Posts