Robolisk
Robolisk

Reputation: 1782

How can I setState in a another components useEffect?

A quick view of what I'm trying to do:

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

const MainComponent = () => {
  const [element, setElement] = useState([]);
  const [setThings] = useSomething();
  useEffect(() => {
    setThings(element);
  }, [element]);
};

const useSomething = () => {
  const [things, setThings] = useState([]);
  // do stuff now that you've received things
  return [setThings];
};

and another hook in another file. This works perfectly fine, and is an excellent solution for working with a canvas in reactjs. I have a warning that is throw and I can't seem to sort it out with my research:

  Line 150:7:  React Hook useEffect has a missing dependency: 'setThings'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

In the react docs it says this causes issues because the it is calling something that has depencancy's but I'm unse where they are?

Upvotes: 0

Views: 51

Answers (1)

michael
michael

Reputation: 4173

Try to add setThings to dependencies array in useEffect.

useEffect(() => {
  setThings(element);
}, [element, setThings]);

Upvotes: 1

Related Questions