Stas Motorny
Stas Motorny

Reputation: 195

useState hook causes "too many rerenders" error when using it in react-native

I just started with React-native and I can't understand why I got error "too many rerenders". So I created app using npx react-native init command and than I changed App.js, now my App.js looks like that:

const App = () => {
    const [numberOne, setNumberOne] = useState(0);
    const [numberTwo, setNumberTwo] = useState(0);

    setNumberOne(5);
    setNumberTwo(7);

    return (
        <View>
            <Text>Number one is {numberOne}</Text>
            <Text>Number two is {numberTwo}</Text>
        </View>
    )
};

Also I was trying to use seters inside a function but got same error:

const App = () => {
    const [numberOne, setNumberOne] = useState(0);
    const [numberTwo, setNumberTwo] = useState(0);

    const set = () => {
        setNumberOne(5);
        setNumberTwo(7);
    };

    set();

    return (
        <View>
            <Text>Number one is {numberOne}</Text>
            <Text>Number two is {numberTwo}</Text>
        </View>
    )
};

Why is this happens and how to fix it?

Upvotes: 3

Views: 296

Answers (1)

dglozano
dglozano

Reputation: 6607

You are changing the component's state when it renders. Also, when a component's state changes, it will render again. Thus, you are getting an infinite loop of renders.

Renders => updates state on render => renders again because the state changed => updates state again because it rendered again => ...

What you can probably try is something like this:


const App = () => {
    const [numberOne, setNumberOne] = useState(0);
    const [numberTwo, setNumberTwo] = useState(0);

    useEffect(() => {
        setNumberOne(5);
        setNumberTwo(7);
    }, []);

    return (
        <View>
            <Text>Number one is {numberOne}</Text>
            <Text>Number two is {numberTwo}</Text>
        </View>
    )
};

That will schedule an effect to be run only after the first render, because you are passing an empty dependencies array as second argument of the useEffect hook.

You don't have to define a setter, your setNumberOne and setNumberTwo are already "setters", that then you can use in event handlers

Upvotes: 3

Related Questions