skip to Main Content

For example, from the documentation (https://reactjs.org/docs/hooks-effect.html) –

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

However this would not work:

import React, { useEffect } from 'react';

function Example() {
  var count = 0;

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => count = (count + 1)}>
        Click me
      </button>
    </div>
  );
}

What requires us to use the useState call? What are the advantages?

3

Answers


  1. It’s more related on how change detection works in React.

    Rendering is triggered after changes in the local state using hooks likes useState/useReducer or in your component props.

    If you don’t use useState hook to change the state the rendering will not be triggered and you will not see the changes on your view

    useEffect will execute after each render

    1. dom updated
    2. page painted
    3. useEffect cleanup
    4. useEffect execute and change the state
    5. another render is triggered with the new state
    Login or Signup to reply.
  2. If you modify the state directly react doesn’t notice the change and therefore useEffect is not called.

    Changing the state in react directly is always a bad practice you should always use the set method of useState because otherwise react will not notice the change. Therefore things like rendering the value and useEffect won’t work.

    Basically if you directly update the state nothing will change.

    Login or Signup to reply.
  3. The simplest answer is that you need a hook.

    In React, hooks are functions that give you access to different React features while a React component is rendering.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search