I present two different ways to render an input component;
<code>
E.g.1 | E.g. 2
function myComponent(){ | function StateHelper(){
const [st, setSt] = useState(''); | const [st, setSt] = useState('');
|
render <div> | return {context: {st, setSt}}
{Math.random()} | }
<input value={st} |
onChange={e=>setSt(e.target.value)/> | function myComponent(props){
</div> |
| const {context} = StateHelper();
|
| render <div>
| {Math.random()}
| <input value={context.st}
| onChange=(e=>context.setSt(e.target.value)/>
| </div>
| }
</code>
<code>
E.g.1 | E.g. 2
function myComponent(){ | function StateHelper(){
const [st, setSt] = useState(''); | const [st, setSt] = useState('');
|
render <div> | return {context: {st, setSt}}
{Math.random()} | }
<input value={st} |
onChange={e=>setSt(e.target.value)/> | function myComponent(props){
</div> |
| const {context} = StateHelper();
|
| render <div>
| {Math.random()}
| <input value={context.st}
| onChange=(e=>context.setSt(e.target.value)/>
| </div>
| }
</code>
E.g.1 | E.g. 2
function myComponent(){ | function StateHelper(){
const [st, setSt] = useState(''); | const [st, setSt] = useState('');
|
render <div> | return {context: {st, setSt}}
{Math.random()} | }
<input value={st} |
onChange={e=>setSt(e.target.value)/> | function myComponent(props){
</div> |
| const {context} = StateHelper();
|
| render <div>
| {Math.random()}
| <input value={context.st}
| onChange=(e=>context.setSt(e.target.value)/>
| </div>
| }
I seem to be confused on one of the fundamentals.
On e.g. 1, when I type, I don’t lose focus on the input component.
On e.g. 2, on each letter typed, I lose focus.
On both of these examples, Math.random() changes, so they both re-render.
I don’t know what’s the difference, and why I keep losing focus on e.g. 2 ?
I’m trying to follow e.g. 2 as it helps me manage my code better, why is it happening, what am I not understanding about react component re-rendering and how can I fix it?