I am using context api and hooks, there are 20 state variables, in each changes (setting states) the function calls again or re-renders so my concern is about calling hooks functions.
Example if I use useState, useReducer, useMemo, useCallback
are they called again per any re-render?
function GroupProvider(props) {
const socket = useMemo(()=> io(url), [socket]);
const [grouplist, setGrouplist] = useState([]);
const [refreshid, setRefreshid] = useState('');
const [messages, setMessages] = useState({});
const [ppl, setPpl] = useState(people);
const [groupname, setGroupname] = useState(name);
const [groupimg, setGroupimg] = useState(img);
const [groupnamesaving, setGroupnamesaving] = useState(false);
const [groupimgsaving, setGroupimgsaving] = useState(false);
const [editgroupname, setEditgroupname] = useState(false);
const [addingmember, setAddingmember] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [leavinggroup, setLeavinggroup] = useState(false);
const [changeAdminModal, setChangeAdminModal] = useState(false);
const [changingAdmin, setChangingAdmin] = useState(false);
const [loadingModal, setLoadingModal] = useState(false);
}
Here if in each re-rendering, hooks function calls, so it may affect on performance.
Yes they are called on each render, in the first render it initialise a memory cell, on re-render it read the value of the current cell :
When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.
https://reactjs.org/docs/hooks-faq.html#how-does-react-associate-hook-calls-with-components
Always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders.
Ref link:- https://reactjs.org/docs/hooks-rules.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With