React.js most important concepts with example

 



1. React State Management:

  • useState vs. useReducer:

    • useState is useful for managing simple state values like numbers, strings, or objects. It's straightforward and works well for local state.


      const [count, setCount] = useState(0);
    • useReducer is useful when state logic becomes complex or involves multiple sub-values. It also helps manage complex state transitions.


      const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; default: return state; } }; const [state, dispatch] = useReducer(reducer, { count: 0 });

2. Performance Optimization:

  • Common Techniques:

    • Lazy loading components using React.lazy and Suspense to reduce the initial load time.

    • Memoization using useMemo and React.memo to avoid unnecessary re-renders.

    • Code splitting to load only the necessary components for specific routes.

  • React.memo and useMemo:

    • React.memo is a higher-order component that prevents a component from re-rendering if its props haven’t changed.


      const MemoizedComponent = React.memo(MyComponent);
    • useMemo memoizes expensive computations and recalculates only when dependencies change.


      const expensiveResult = useMemo(() => computeExpensiveValue(), [dependencies]);

3. React Hooks:

  • useEffect and Dependency Array:

    • useEffect runs after the render and performs side effects like data fetching or updating the DOM.

      • The dependency array determines when useEffect is triggered. If the array is empty, it runs only once (on mount).


      useEffect(() => { // Code here runs on every render. }, [dependency]); // Runs only when dependency changes.
  • useRef vs. useState:

    • useRef holds a mutable reference that persists across renders but doesn’t trigger a re-render when updated.

    • useState holds state that causes re-renders when updated.


      const myRef = useRef(null); // For accessing DOM elements or mutable variables. const [state, setState] = useState(0); // For reactivity.

4. Component Lifecycle in Functional Components:

  • Lifecycle Handling:

    • Functional components handle lifecycle methods using hooks:

      • useEffect mimics componentDidMount, componentDidUpdate, and componentWillUnmount.

  • useLayoutEffect vs. useEffect:

    • useLayoutEffect runs synchronously after all DOM mutations and before the browser paints, which is useful for measuring layout changes.

    • useEffect runs asynchronously after the DOM updates.

5. Routing:

  • Dynamic Routes in React Router:

    • Dynamic routes are created using :paramName in the path.


      <Route path="/user/:id" component={UserProfile} />

      You can access route parameters using the useParams hook.


      const { id } = useParams();
  • Nested Routes and Parameters:

    • You can define nested routes by using <Outlet /> in the parent component.


      <Route path="/dashboard" element={<Dashboard />}> <Route path="settings" element={<Settings />} /> </Route>

6. Forms and Input Handling:

  • Form Validation:

    • Libraries like Formik or React Hook Form help with form validation:

      • Formik provides easy state management and validation handling:


        <Formik initialValues={{ email: '' }} onSubmit={values => console.log(values)} > {({ handleChange, handleSubmit, values }) => ( <form onSubmit={handleSubmit}> <input name="email" value={values.email} onChange={handleChange} /> <button type="submit">Submit</button> </form> )} </Formik>
  • Controlled vs. Uncontrolled Inputs:

    • Controlled: State controls the input value.

      const [value, setValue] = useState(''); <input value={value} onChange={(e) => setValue(e.target.value)} />
    • Uncontrolled: The DOM manages the input value, accessed using useRef.

      const inputRef = useRef(null); <input ref={inputRef} />

7. Styling in React:

  • Ways to Style React Components:

    • CSS Modules: Scoped styles.

    • Styled-components: CSS-in-JS library.

    • Tailwind CSS: Utility-first CSS framework for consistent styling.

  • Conditional Styling:

    • You can conditionally apply styles based on state or props.

      const isActive = true; return <div className={isActive ? 'active' : 'inactive'}>Content</div>;

8. Testing in React:

  • Unit Tests with Jest/React Testing Library:

    • Use Jest for unit tests and React Testing Library for testing component behavior.

      test('renders a button', () => { render(<MyComponent />); const buttonElement = screen.getByRole('button'); expect(buttonElement).toBeInTheDocument(); });
  • Shallow Rendering vs. Full DOM Rendering:

    • Shallow rendering renders only the component, without its child components. Useful for unit tests.

    • Full DOM rendering renders the component along with its children, simulating a more realistic DOM.

9. Custom Hooks:

  • Creating Custom Hooks:

    • Custom hooks allow you to extract reusable logic. For example, a useFetch hook for fetching data:

      function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then(response => response.json()) .then(data => setData(data)); }, [url]); return data; }
  • Use Cases:

    • Fetching data, managing timers, or dealing with form validation logic.

10. State Management Libraries:

  • Redux with React:

    • Redux is a state management library that centralizes the state in a store.

      const store = configureStore({ reducer: rootReducer });

      Use useSelector to access state and useDispatch to dispatch actions.

  • Redux Toolkit vs. React Context:

    • Redux Toolkit simplifies Redux logic with built-in best practices.

    • React Context is great for simple global state but becomes less efficient for complex state with frequent updates.

Post a Comment

Previous Post Next Post