Generative Data Intelligence

Use key props in react

Date:

According to react home page so

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

Keys can be understood as id in the dom which help to identify elements and query elements. Keys are often used when rendering list. But what else keys can do? In my case I usually use keys to reset states when navigating between multiple pages using the same component but different data. Let’s see two examples below

Reset List component which shows data based on ID

  • This case we will have a component called List and the component will show a list of items which are normally fetched from server. The component can also have search, filter function and load more function.
  • The List component will also show different data based on the current page, for example if you are browsing different categories in an ecommerece site or a news site.
  • To do these function then you will normally have a bunch of state to store the search params, paging information.
  • When you move to another page let say/page/:pageId. The List will need to reset its state. The easiest way I usually do is to give the component the id from the pageId as <List key={List_${pageId}} />. By this way react will handle reset logic for you, if you want to do it your self then you will need an useEffect to reset the internal state.
  • It is common to have a Form component which can be used for creating and for editing and this form will need to reset its state between navigating objects.
  • If you use form libraries like formik or react-hook-form then you will need to sync between internal form state which is managed by the lib and your data which can be in context or redux.
  • With this case I usually create a Form component for wrapping UI and logics inside, this Form will be rendered with key is the id of the object as <Form data={data} key={form_${data.id}} />. By this way you often do not need to reset your form state when you switch between data object.
  • If you do not use the key props then you will need to useEffect with dependency to the data and when the data is changed you will need to apply the current form state to this data.

Keys are powerful inside list rendering and reseting states for components showing same data types.

this post is originally posted here https://www.hittaducmai.se/blogs/use-key-props-in-react

spot_img

Latest Intelligence

spot_img

Chat with us

Hi there! How can I help you?