I'm making an app where you can practice your math I have a function that returns two random numbers on the render of the page and I pass down input to collect the user's answer in estate it has a change that runs the setusersAnswer() to the value entered in the input. but the problem is that every time I enter something it re-renders the entire question on every change made to the input component users answer.
here is the function in my component :
const Question = ({input}) => {
const makeQuestion = () => {
firstNumber = randomRange();
secondNumber = randomRange();
return <>{`${firstNumber} +${secondNumber}`}</>;
};
return (<>
{makeQuestion()}
{input}
</>)}
export default Question;
in my app js, I have a text input:
app.js:
function App() {
const [UserAnswer, setUserAnswer] = useState('')
const handleUserAnswer=(val)=>{
setUserAnswer(val);
}
return(
<Question input={<Input handleUserAnswer={handleUserAnswer}/>} />
)}
my input component looks like this :
const Userinput = ({handleUserAnswer}) => {
return (
<Input onChange={handleUserAnswer}>
)}
now I cleaned up this code so there are only the basic parts here is a visual representation of what the issue is:
if I enter anything into the input it triggers a rerender and different The random number function runs again.
it triggers a re-render of the whole UI which I don't want. I want to store the user's answer without triggering a re-render.
As to the question in the title - no. Setting state fundamentally will trigger a re-render; React's view is designed to flow directly from the state, so when the state changes, the view is supposed to change too.
As to the body of your question - it looks like a simple tweak that would get you what you want would be to create firstNumber and secondNumber only once, regardless of re-renders. Since they don't ever change for a given component, they could be either state or a ref.
const Question = ({ input }) => {
const [numbers] = useState(() => [randomRange(), randomRange()]);
return (<>
{`${numbers[0]} +${numbers[1]}`}
{input}
</>)
}
export default Question;
There will still be re-renders, but now that the random numbers have only been generated once, the re-renders won't cause problems. (Don't be afraid of re-rendering. It's not often problematic.)