Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a function within useState

I'm using React Sortable HOC to move items around. My initial state is an empty array and I need to update the state with a function from React Sortable.

This is the original snippet from React Sortable HOC

onSortEnd = ({oldIndex, newIndex}) => {
    this.setState(({items}) => ({
      items: arrayMove(items, oldIndex, newIndex),
    }));
  };

My state and function look like this

const [colors, setColors] = useState([])

function onSortEnd({ oldIndex, newIndex }) {
  setColors([...colors, ({ colors }) => ({
     colors: arrayMove(colors, oldIndex, newIndex)
  })]);
};

What ends up happening is no errors, but more colors get added when I attempt to arrange any existing color.

like image 600
Dave.Q Avatar asked Sep 03 '19 02:09

Dave.Q


People also ask

Can I use function inside useState?

Rules for using useState You'll get an error. The first rule means that, even inside functional components, you shouldn't call useState in loops, conditions, or nested functions because React relies on the order in which useState functions are called to get the correct value for a particular state variable.

Can I store function in state?

Equipped with these solutions, you can store and mutate functions in state hooks without mysterious crashes and cryptic error messages. However, you should take care not to overuse it.

Can you initialize useState from a function?

With the useState hook, you can pass a function as an argument to initialize the state lazily. As discussed, the initial value is needed only once at the first render.

What is the best practice to use function useState hook?

UseState works just as class component's state Depending on how frequently your application's data changes, it's a good idea to break state into multiple variables. As a rule of thumb, it's best to keep each state separate so that it's easy to update and submit the data.


1 Answers

Based on the requirement mentioned, I think you don't need the callback format for setState and you can simply do

const [colors, setColors] = useState([])

function onSortEnd({ oldIndex, newIndex }) {
  const newColors = arrayMove(colors, oldIndex, newIndex);
  setColors(newColors);
};
like image 62
Milind Agrawal Avatar answered Oct 23 '22 11:10

Milind Agrawal