In my test app, every time a certain function is called, a call to my API is made (axios.get) and then two state variables are updated with the data received from the database. These two state variables both change a part of what is shown on the screen.
The things is, I added a useEffect hook to "debug" the amount of re-renders and I noticed that the component is re-rendered twice, I guess because it is once for one state variable and once for the other one. I thought using useReducer would change this, but it doesn't.
Is this a normal React behaviour or is there something I should be doing differently in order for the component is re-rendered only once?
Edit: I am editing to add the code: (It's a trivia kind of test app, I'm new to React, so I am practicing)
import React, { useEffect, useReducer } from 'react'
import axios from 'axios'
import './App.css';
import reducer from './Reducer.js'
const initialState = {
question: '',
id: 1,
choices: []
}
const Questions = () => {
const [state, dispatch] = useReducer(reducer, initialState)
useEffect(() => {
console.log('executed');
})
const getQuestion = async (e) => {
try {
e.preventDefault()
const res = await axios.get(`/questions/${state.id}`)
dispatch({
type: 'set_question',
payload:
res.data.question
})
dispatch({
type: 'set_choices',
payload:
[res.data.correct_answer,
res.data.incorrect_answer1,
res.data.incorrect_answer2]
})
} catch (err) {
console.log(err);
}
}
return (
<div>
<form onSubmit={getQuestion}>
<button>Get next question</button>
</form>
<h1> {state.question ? state.question : null}</h1>
<button> {state.choices ? `${state.choices[0]}` : null}</button>
<button> {state.choices ? ` ${state.choices[1]}` : null}</button>
<button> {state.choices ? ` ${state.choices[2]}` : null}</button>
</div>
)
}
export default Questions
Reducer:
const reducer = (state, action) => {
switch (action.type) {
case 'set_question':
return {
...state,
question: action.payload
}
case 'set_choices':
return {
...state,
choices: action.payload
}
default:
return state
}
}
export default reducer