React: support loop and condition in react hooks

Created on 21 Dec 2018  路  4Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?
feature
What is the current behavior?

Don鈥檛 call Hooks inside loops, conditions, or nested function

What is the expected behavior?

Support useCondition, useLoop and so on.

We need to make small states hooks through useCondition& useLoop to form a large state hooks.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

React 16.7.0.alpha


for example

import { useState, useCallback } from 'react';

interface FooHooks {
  foo: number;
  setFoo: (x: number) => void;
}
const useFoo = (): FooHooks => {
  const [foo, setFoo] = useState<number>(1);
  const setFooWithLog = useCallback((x: number) => {
    console.log(x);
    setFoo(x);
  }, []);
  return { foo, setFoo: setFooWithLog };
};

const useFooList = (fooListLength: number): FooHooks[] => {
  throw new Error('TODO');
};

Could you tell me how to write useFooList?

All 4 comments

If the list never changes length, you can literally do.

const useFooList = (fooListLength: number): FooHooks[] => {
  const hooks: FooHooks[] = [];
  for (let i = 0; i < fooListLength; i++) {
    hooks[i] = useFoo();
  }
  return hooks;
};

If it does change length you should probably write a reducer.

I thought hooks weren't meant to be called inside loops like this?

They aren't supposed to as a general rule to avoid bugs, but as long as all of the same hooks are called in the same order each time, it'll work as expected.

This is not something we intend to support. You can split a single item in its own component and then it'll "just work".

Was this page helpful?
0 / 5 - 0 ratings