DEV Community

Vikrant Patel
Vikrant Patel

Posted on

React’s useEffect and useState Hooks

useEffect and useState are React's most useful hooks. Let's drill down to understand the use of it.

useState

useState

Follow through the example above:
First, you must import the destructuring useState hook from React.
Then we call the useState hook from within the counter function. The React useState returns the Value of '0' and the Counter function updates it with count and setCount.

In Short,

The React Hook useState accepts the assigned state and returns two values:
1) The current state.
2) A function that will update the state.

The fun fact is that useState Hook can be declared with any type of state variable and can be used multiple times in a single component.

useEffect:

You must be familiar with fetching data, and updating DOM and timers, these side effects in your component can be handled by useEffect Hook in React as well.

But there is a catch here,

useEffect runs on every render. In the above example when useEffect is hooked the count will change, app rerender and then triggers one after another effect.

To avoid this behavior we should always include a second parameter that accepts an array. Optionally, pass dependencies to useEffect in this array.

Let's look at some examples;

  1. No dependency passed:
    No dependency passed

  2. An empty array:

An empty array

  1. Props or state values:

Props or state values

for initial rendering:

initial rendering

If the count variable updates, the effect will run again:

count variable update

Effect Cleanup:

Some side effects require no re-use factor, such as timeouts, and event listeners.
Including the return function at the end of the useEffect will dispose of the purpose of re-rendering.

Example:
Cleanup

Top comments (0)