J
J
Juniorrrrr2020-02-13 15:18:12
JavaScript
Juniorrrrr, 2020-02-13 15:18:12

How to properly use the useEffect hook?

Good day. Often you have to write hooks like this

useEffect(() => {
      dispatch(
        someAction({ ...params, anotherParams, page}),
      )
  }, []);

And for example, it is necessary to dispatch the action only once when mounting the component, and everything seems to work, but the linter starts to swear, they say , insert params , anotherParams , page and dispatch into dependencies, and of course, if you do this, then the pain begins.
In classes, in this regard, it was easier to write code.
5e453e12ede37539280143.png

Tell me experienced people, how do you solve such moments?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
profesor08, 2020-02-13
@Juniorrrrr

First, useEffect will always fire when the component is rendered. Update the request or state and be sure useEffect will be called. This means that you need to enter an internal state for the component, indicating that it is rendered.

const Comp = () => {
  const [ready, setReady] = useState(false);
  const dispatch = useDispatch();

  useEffect(() => {
    if (ready === false) { // после отображения элемента будет вызвана функция, `ready` все еще будет `false`, поэтому выполнив свой код, надо вручную задать ей true, чтоб код не вызывался дважды.
      dispatch({ type: 'increment-counter' });
      setReady(true);
    }
  });
};

The error asks you to remove `[]` from the call to useEffect
How to use hooks in redux is written here, with examples:
https://react-redux.js.org/next/api/hooks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question