user11114318
user11114318

Reputation:

How to set inital state as props in react with hooks?

I want to set state as props in react using hooks and I'm getting error: Too many re-renders. React limits the number of renders to prevent an infinite loop. ▶ 34 stack frames were collapsed.

My code: First Component :

const List = () => {
    const [items, setItems] = useState([{}])
    useEffect(() => {
        const fetchData = async () => {
            const data = await fetch(
                'http://localhost:5000/api',
            );
            const result = await data.json();
            setItems(result);
        };
        fetchData();
    }, []);
   return (
          <ActualList items={items}/>
    )
}

and the second component:

const ActualList = props => {
    const [items, setItems] = useState([{}])
    setItems(props.items)
    }
...

Upvotes: 0

Views: 281

Answers (3)

user11114318
user11114318

Reputation:

So I eventually figured out how to do this, in case someone needs it here is the code :

const [items, setItems] = useState([{}]);
useEffect(() => setItems(props.items), [props])

Upvotes: 1

Doğancan Arabacı
Doğancan Arabacı

Reputation: 3982

You are calling setItem in every render. Each time you change a state value, your component will be re-rendered, which will cause another state change, another re-render....

You should conditionally call setItems

Upvotes: 1

Stundji
Stundji

Reputation: 864

You can directly pass props to useState:

const ActualList = props => {
    const [items, setItems] = useState(props.items) // pass props.items as an initial state
    }

Upvotes: 1

Related Questions