use state

 =

The useState hook in React is used to create a state variable within a functional component. It allows you to set and update values over time, and any changes trigger a re-render of the component to reflect the new state.

In Vue, state is managed using data properties within the component’s options. While React's useState is function-based, Vue's data properties are object-based, but both work to manage reactive values in their respective frameworks.

React: useState Hook
In React, useState initializes state and returns an array with two elements:

The current state value.
A function to update that state.
Basic Example in React:

javascript
Copy code
import { useState } from 'react';

function Counter() {
  // Initialize state variable `count` with a value of 0
  const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
Explanation:

useState(0) initializes count to 0.
setCount is used to update the count state.
Whenever setCount is called, the component re-renders, displaying the new count value.
Vue: State Using data
In Vue, data is an object that holds the components state properties. These properties are reactive by default, meaning changes to data trigger reactivity in the component.

Basic Example in Vue:

javascript
Copy code
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0 // Initialize state variable `count` with a value of 0
    };
  },
  methods: {
    increment() {
      this.count += 1; // Update `count` to trigger reactivity
    }
  }
}
</script>
Explanation:

data() returns an object where count is initialized to 0.
The increment method modifies count directly (this.count += 1).
Any changes to count automatically trigger reactivity, updating the view.
Comparison of useState in React and Vues data
React useState  Vue data
Initializes state in functional components. Initializes state in data() method.
Returns an array [state, setState]. Uses properties on the returned data object.
Changes state using setState(). Changes state by directly updating this properties.
Requires importing useState from React. data is part of Vues component options.
Both approaches work to manage reactive data within components, though Reacts useState is specific to functional components while Vue uses data for both functional and class-style

=

usecallback

 =

useCallback in React vs. Methods in Vue
Reacts useCallback to memoize functions:

javascript
Copy code
import { useState, useCallback } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
Vue equivalent (methods are automatically cached in Vue):

javascript
Copy code
export default {
  data() {
    return { count: 0 };
  },
  methods: {
    increment() {
      this.count++;
    }
  }
}

=

use memo

 =


useMemo in React vs Computed Properties in Vue

  • React’s useMemo caches expensive computations, only recalculating them when dependencies change.
  • Vue’s computed properties serve the same purpose, caching values and recalculating only when their dependencies change.

Example in Vue:

javascript
export default { data() { return { num1: 5, num2: 10 } }, computed: { sum() { console.log("Calculating sum..."); return this.num1 + this.num2; } } }

=


useMemo in React vs. Computed Properties in Vue
Reacts useMemo to memoize expensive calculations:

javascript
Copy code
import { useState, useMemo } from 'react';

function MyComponent() {
  const [num1, setNum1] = useState(5);
  const [num2, setNum2] = useState(10);

  const sum = useMemo(() => {
    console.log("Calculating sum...");
    return num1 + num2;
  }, [num1, num2]);

  return (
    <div>
      <p>Sum: {sum}</p>
    </div>
  );
}
Vue equivalent using computed properties:

javascript
Copy code
export default {
  data() {
    return { num1: 5, num2: 10 };
  },
  computed: {
    sum() {
      console.log("Calculating sum...");
      return this.num1 + this.num2;
    }
  }
}


=

use reducer

=


useCallback in React vs Methods in Vue

  • React’s useCallback is used to memoize functions so that they don’t get recreated on every render.
  • In Vue, methods are naturally cached between re-renders and only redefined if dependencies within the component change, so you don’t need an equivalent to useCallback.

Example in Vue:

javascript
export default { methods: { fetchData() { console.log("Fetching data..."); } } 

}


use reducer

 =


useReducer in React vs Vuex or Custom State Management

  • React’s useReducer is a way to manage complex state logic in functional components.
  • In Vue, Vuex is typically used to manage complex or global state across components.
  • Alternatively, you can use a custom function to manage state updates similar to useReducer.

Example in Vue: Using Vuex for centralized state management:

javascript
// Vuex store const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ }, decrement(state) { state.count-- } } }); // In a component export default { computed: { count() { return this.$store.state.count; } }, methods: { increment() { this.$store.commit("increment"); } } }

=

useReducer in React vs. Vuex or Custom State Management in Vue
Reacts useReducer to manage complex state logic:

javascript
Copy code
import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'decrement': return { count: state.count - 1 };
    default: return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
}
Vue equivalent using Vuex:

javascript
Copy code
// Vuex store
const store = new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state) { state.count++; },
    decrement(state) { state.count--; }
  }
});

// In a Vue component
export default {
  computed: {
    count() { return this.$store.state.count; }
  },
  methods: {
    increment() { this.$store.commit("increment"); }
  }
}

=

use ref

 

useRef in React vs Refs in Vue

  • React’s useRef is used to create a reference to a DOM element or a value that doesn’t trigger re-renders when changed.
  • Vue’s ref directive also lets you directly access DOM elements or store values that don’t cause reactivity when changed.

Example in Vue:

html
<template> <input ref="myInput" /> </template> <script> export default { mounted() { this.$refs.myInput.focus(); // Directly access DOM element } } </script>
=
useRef in React vs. Refs in Vue
React’s useRef to access a DOM element or store values:

javascript
Copy code
import { useRef, useEffect } from 'react';

function MyComponent() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus(); // Focus the input on mount
  }, []);

  return <input ref={inputRef} />;
}
Vue equivalent:

html
Copy code
<template>
  <input ref="myInput" />
</template>

<script>
export default {
  mounted() {
    this.$refs.myInput.focus(); // Directly access DOM element
  }
}
</script>

=

use context

 =

useContext in React vs Provide/Inject in Vue

  • React’s useContext is used to access shared data across the component tree without passing props down manually.
  • Vue’s provide and inject do the same by letting parent components provide values that children can access without needing to pass props.

Example in Vue:

javascript
// Parent Component export default { provide() { return { sharedData: this.dataValue } }, data() { return { dataValue: "Hello from Parent" } } } // Child Component export default { inject: ["sharedData"], mounted() { console.log(this.sharedData); // "Hello from Parent" } }

=


useContext in React vs. Provide/Inject in Vue
Reacts useContext to share data across the component tree:

javascript
Copy code
import React, { createContext, useContext } from 'react';

const MyContext = createContext("Hello from Context");

function Parent() {
  return (
    <MyContext.Provider value="Hello from Parent">
      <Child />
    </MyContext.Provider>
  );
}

function Child() {
  const sharedData = useContext(MyContext);
  return <p>{sharedData}</p>; // Outputs: "Hello from Parent"
}
Vue equivalent:

javascript
Copy code
// Parent Component
export default {
  provide() {
    return {
      sharedData: "Hello from Parent"
    };
  }
}

// Child Component
export default {
  inject: ["sharedData"],
  mounted() {
    console.log(this.sharedData); // "Hello from Parent"
  }
}

=

use effect

 =

useEffect in React vs Watchers and Lifecycle Hooks in Vue

  • React's useEffect runs code after a component renders or re-renders and can react to dependency changes or perform clean-up actions.
  • Vue's watch and lifecycle hooks like mounted, beforeDestroy, etc., provide similar functionality:
    • Watchers are similar to useEffect with dependencies in that they let you run code in response to specific reactive data changes.
    • Lifecycle Hooks can handle actions on mount, update, or before unmounting the component.

Example in Vue:

javascript
export default { data() { return { count: 0 } }, watch: { count(newVal) { console.log("Count changed to:", newVal); } }, mounted() { console.log("Component mounted"); } }

=



useEffect in React vs. Watchers and Lifecycle Hooks in Vue
Reacts useEffect to run code on mount or when dependencies change:

javascript
Copy code
import { useState, useEffect } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component mounted or count changed:", count);

    return () => console.log("Cleanup code runs when component unmounts or count changes");
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Vue equivalent:

javascript
Copy code
export default {
  data() {
    return { count: 0 }
  },
  watch: {
    count(newVal) {
      console.log("Count changed to:", newVal);
    }
  },
  mounted() {
    console.log("Component mounted");
  },
  beforeUnmount() {
    console.log("Cleanup before component unmounts");
  }
}

=



=

state hook

 =

There are 3 rules for hooks:

  • Hooks can only be called inside React function components.
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional
state accepts two values
initialise withsoem value
The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these!

import React, { useState } from "react";
import ReactDOM from "react-dom/client";

function FavoriteColor() {
  const [color, setColor] = useState("red");

  return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button
        type="button"
        onClick={() => setColor("blue")}
      >Blue</button>
      <button
        type="button"
        onClick={() => setColor("red")}
      >Red</button>
      <button
        type="button"
        onClick={() => setColor("pink")}
      >Pink</button>
      <button
        type="button"
        onClick={() => setColor("green")}
      >Green</button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);

=


update only color of car 



import { useState } from "react";
import ReactDOM from "react-dom/client";

function Car() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red"
  });

  const updateColor = () => {
    setCar(previousState => {
      return { ...previousState, color: "blue" }
    });
  }

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
      <button
        type="button"
        onClick={updateColor}
      >Blue</button>
    </>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);=

=


=

css styling

 =

import React from 'react';
import ReactDOM from 'react-dom/client';

const Header = () => {
  return (
    <>
      <h1 style={{color: "red"}}>Hello Style!</h1>
      <p>Add a little style!</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);

=

const Header = () => {
  const myStyle = {
    color: "white",
    backgroundColor: "DodgerBlue",
    padding: "10px",
    fontFamily: "Sans-Serif"
  };
  return (
    <>
      <h1 style={myStyle}>Hello Style!</h1>
      <p>Add a little style!</p>
    </>
  );
}

=

sass styling


import React from 'react';
import ReactDOM from 'react-dom/client';
import './my-sass.scss';

const Header = () => {
  return (
    <>
      <h1>Hello Style!</h1>
      <p>Add a little style!.</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);

=

$myColor: red;

h1 {
  color: $myColor;
}



=

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...