The question applies for both Class and function based components. This is probably an way too easy question, but for some reason I can't find a concise definite answer so I sometimes get thrown off. All I can find is 'the component re-renders' but what does it actually mean? rendering is re-examine the state of the component to describe how to paint the DOM, but does it also re-define any referenced data-types within the component? Or will it only re-invoke the render() method on Class component?
In the functional component. Does it mean 'languages' array, 'updateLanguage' function, and everything I might put in is re-defined? Or only what is defined in the return body? (like inline arrow handlers, etc...). I know we can use useCallback to prevent re-renders for stuff like handlers, but that is a different question.
const App = () => {
const [selectedLang, setSelectedLang] = useState('');
const languages = ['All', 'JavaScript', 'Ruby', 'Java', 'Python'];
const updateLanguage = lang => setSelectedLang(lang);
console.count('render');
return (
<ul>
{languages.map(lang=> (
<li key={lang}>
<button
className={`${selectedLang == lang && 'btn-selected'}`}
onClick={() => updateLanguage(lang)}
>
{lang}
</button>
</li>
))}
</ul>
);
};
and with this Class based example, all of the instance methods will be re-defined on every render? or only stuff inside render() method?
class Languages extends Component {
constructor(props){
super(props);
this.state = {selectedLanguage: 'All'};
this.updateLanguage = this.updateLanguage.bind(this);
}
updateLanguage(lang){
this.setState({selectedLanguage: lang});
}
render(){
const languages = ['All', 'JavaScript', 'Ruby', 'Java', 'Python'];
const {selectedLanguage: selected} = this.state;
console.count('render');
return (
<ul>
{languages.map(lang=> (
<li key={lang}>
<button
className={`${selected == lang && 'selected'}`}
onClick={() => this.updateLanguage(lang)}
>
{lang}
</button>
</li>)
)}
</ul>
)
}
}