React.js Quick Notes

July 28, 2024

React Styling

  • There are many ways to use styles in React.
  1. You can create a new css file for every component. The classes you create will be global and will not be limited to the target JSX file.
  2. CSS Modules can help you limiting the scope. Selector names will be generated dynamically
  3. External Package: Styled Components
  4. Inline CSS (if you're high)
  5. Use a damn library (Tailwind CSS, Material UI...)

React Essentials

  • React.StrictMode can be added to the App component to identify some errors. If added and you try to log a state, you'll see it logging twice because react will render the component twice.
  • Do not use the current state directly in setState method. setState() accepts a function, whose parameter will be the current state. Make necessary changes in that function and return the state.
  • State Uplift: Lift the state up to the parent component if it should be accessed by a sibling component. Pass state update functions via props from parent component.
  • useRef can be used to get access to DOM elements (for both current and child components). To read input values of child component, you must create a useRef and pass it to child. Child component should be wrapped under forwardRef and the second argument will the ref.
  • useImperativeHandle can help you in decoupling. For example, a modal can be opened by calling showModal(). You need to close if from parent. You use modal.current.showModal(). This dependency can be removed by this feature.
  • Portals can be used to place HTML elements anywhere in the DOM. For example you'd want to render a modal/popup directly under body tag instead of putting it under nested elements.
  • Creates as less states as you can.

React Context API

  • Context helps in reducing the prop drilling of states and state updating functions.
  • You create a context using createContext in store file, consume the context using useContext.
  • Wrap the App component, or whichever parent component that needs access to the data we put in context with a Provider.