Skip to content

Best practices React

  1. Document reusable components fe storybook
  2. Avoid anonymous functions in the render methods of a flatlist, sectionlist, … or in the props of a component because this creates a new function at every rerender
  3. Do not use an index as a key in a list for performance
  4. Initialise the state always with the type of element you expect instead of null (to avoid for example a map function to throw an error when expecting an array)
  5. setState is asynchronous, so do not rely on current state. Use a function or useState
  6. Typecheck your components: typescript, flow or proptypes
  7. Do not use async in forEach. It fires off multiple asynchronous calls, but the function immediately returns after that and doesnt await the answers.If you want to execute the function in sequence, use a modern for … of loop instead, in which await will work as expected:

    async function printFiles () { const files = await getFilePaths(); for (const file of files) { const contents = await fs.readFile(file, ‘utf8’); console.log(contents); } }If you want to read the files in parallel, use map instead, and you can await the array of promises that you’ll get with Promise.all:

    async function printFiles () { const files = await getFilePaths(); await Promise.all( (file) => { const contents = await fs.readFile(file, ‘utf8’) console.log(contents) })); }

  8. Import correctly
  9. Use a production build for users and a development build while developing (You can check this with the react developer tools. If the icon has a red background , it is in development mode. If black, production.
  10. Never adapt the state itself. Make a copy (cloneDeep if necessary) or use immutable data
  11. Use normalizr to avoid a nested store
  12. use selectors in redux for memoization
  13. Async await instead of promises
  14. Fat arrow instead of bind
  15. Enable React strict mode to get extra warnings. This has no effect on production.
  16. Add eslint checks

Usedul links:
Immutable data in React (video)
Bet practices
Node js best practices

Published inReact

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *